您可以使用以下脚本执行此操作(阅读 cmets)
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 中,您可以在想要显示工具提示时阅读它:
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。
https://jsfiddle.net/3ojet4oL/9/