鼠标悬停时SVG Map工具提示,点击能力

时间:2016-06-15 07:59:01

标签: javascript html css dictionary svg

我创建了一个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); 
}

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

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

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/

<强>更新

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

    <path class="HI-map maui" data-tooltip="tooltip10"
    

    <强>的javascript

     tooltip.innerText = item.getAttribute('data-tooltip');
    

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

    1. 对于工具提示将随光标移动,您只需使用mousemove事件:
    2. item.addEventListener('mousemove', function(e) {
        tooltip.style.top = e.clientY + 'px';
        tooltip.style.left = e.clientX + 'px';
      });
      

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

      更新2

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

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