鼠标悬停时的 SVG 地图工具提示,单击功能

spj*_*pjy 4 html javascript css svg dictionary

我创建了一个 SVG 地图,但是,我想让它在有人悬停在它上面时有一个工具提示(跟随鼠标)并且每个路径都是唯一的。除了有一个工具提示,我希望每个 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); 
}
Run Code Online (Sandbox Code Playgroud)

这是我的 SVG:https : //jsfiddle.net/3ojet4oL/

感谢您的帮助!

Mos*_*Feu 6

您可以使用以下脚本执行此操作(阅读评论)

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';
  });
});
Run Code Online (Sandbox Code Playgroud)

查看更新的 jsfiddle:https ://jsfiddle.net/3ojet4oL/3/

更新

  1. 对于动态工具提示文本,有一些方法。其中之一是将文本存储在data-*属性上。在我的例子中data-tooltip,当你想显示工具提示时,你可以阅读它:

html

<path class="HI-map maui" data-tooltip="tooltip10"
Run Code Online (Sandbox Code Playgroud)

javascript

 tooltip.innerText = item.getAttribute('data-tooltip');
Run Code Online (Sandbox Code Playgroud)

刚才看到你要在tooltip里面放一个html。所以我稍微改变了逻辑,你可以在下面的 jsfiddle 中看到。逻辑是将工具提示内容存储在对象中,然后通过data-tooltip属性获取它。

  1. 对于工具提示将随光标移动,您只需要使用mousemove事件:
<path class="HI-map maui" data-tooltip="tooltip10"
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/3ojet4oL/7/

更新 2

对于动态 URL 添加属性data-link,脚本将在新窗口中打开此 URL。

https://jsfiddle.net/3ojet4oL/9/