我创建了一个 SVG map ,但是,我想让它有一个工具提示(跟随鼠标)当有人悬停在它上面并且对每条路径都是唯一的。除了工具提示之外,我还希望每个 SVG 路径都可以点击并在可能的情况下指向一个链接。
我想用这个 CSS 来设计工具提示的样式:
.map-tooltip {
position: absolute;
display: none;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
border:#d3d3d3 solid 1px;
background: #fff;
color: black;
font-family: Comfortaa, Verdana;
font-size: smaller;
padding: 8px;
pointer-events:none;
box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
这是我的 SVG:https://jsfiddle.net/3ojet4oL/
感谢您的帮助!
最佳答案
您可以使用以下脚本执行此操作(阅读评论)
var tooltip = document.querySelector('.map-tooltip');
// iterate through all `path` tags
[].forEach.call(document.querySelectorAll('path.HI-map'), function(item) {
// attach click event, you can read the URL from a attribute for example.
item.addEventListener('click', function(){
window.open('http://google.co.il')
});
// attach mouseenter event
item.addEventListener('mouseenter', function() {
var sel = this,
// get the borders of the path - see this question: http://stackoverflow.com/q/10643426/863110
pos = sel.getBoundingClientRect()
tooltip.style.display = 'block';
tooltip.style.top = pos.top + 'px';
tooltip.style.left = pos.left + 'px';
});
// when mouse leave hide the tooltip
item.addEventListener('mouseleave', function(){
tooltip.style.display = 'none';
});
});
查看更新后的 jsfiddle:https://jsfiddle.net/3ojet4oL/3/
更新
- 对于动态工具提示文本,有一些方法。其中之一是将文本存储在
data-*
属性中。在我的例子中data-tooltip
,那么当你想显示tooltip的时候可以看一下:
html
<path class="HI-map maui" data-tooltip="tooltip10"
javascript
tooltip.innerText = item.getAttribute('data-tooltip');
刚才,我看到你想在工具提示中放一个html。所以我改变了一点逻辑,你可以在下面的 jsfiddle 中看到。逻辑是将tooltip的内容存入object中,通过data-tooltip
属性获取。
- 工具提示会随着光标移动,你只需要使用
mousemove
事件:
item.addEventListener('mousemove', function(e) {
tooltip.style.top = e.clientY + 'px';
tooltip.style.left = e.clientX + 'px';
});
https://jsfiddle.net/3ojet4oL/7/
更新 2
对于动态 URL 添加属性 data-link
脚本将在新窗口中打开此 URL。
关于javascript - 鼠标悬停时的 SVG map 工具提示,可以单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37829412/