【问题标题】:How to display a tooltip div when an SVG element is hovered如何在 SVG 元素悬停时显示工具提示 div
【发布时间】:2018-03-05 04:11:39
【问题描述】:

我需要一个具有“更多信息”图标的内联 SVG 图表,该图标应在悬停时触发“工具提示”。见附件

我设置了工具提示 div 样式并在其他地方使用,但我还需要它来触发 SVG 内的信息图标。

我知道我无法在 SVG 中添加工具提示 html,那么还有哪些其他选项可供我使用?

“图表”只是直接取自图形程序(在本例中为 Sketch)的内联 SVG。我没有使用任何框架或库,如 D3 或 chartjs。请不要建议使用库或框架,因为它不是一个选项。

类似的 SO 问题,但他们没有回答我的问题: How to create an SVG "tooltip"-like box?

【问题讨论】:

  • foreignObject 标签将允许您在 SVG 中添加工具提示 html。链接的答案有什么问题?到目前为止你写了什么代码?有什么问题需要解决?
  • 要求使用自定义工具提示而不是浏览器内置工具提示
  • 向我们展示您已经拥有的代码。你说你有工具提示 div。也提供一些最小的 SVG 标记,即 minimal reproducible example
  • 谢谢。我现在有一个可行的解决方案。

标签: svg tooltip


【解决方案1】:

这很简单。它只需要几行 Javascript。

当我们将鼠标悬停在图标上时,我们定位弹出窗口并显示它。在 mouseout 时,我们再次隐藏它。

还要注意图标上的pointer-events="all",它确保即使对于具有不可见填充的位,鼠标也会被视为“在”图标元素上。

var myicon = document.getElementById("myicon");
var mypopup = document.getElementById("mypopup");

myicon.addEventListener("mouseover", showPopup);
myicon.addEventListener("mouseout", hidePopup);

function showPopup(evt) {
  var iconPos = myicon.getBoundingClientRect();
  mypopup.style.left = (iconPos.right + 20) + "px";
  mypopup.style.top = (window.scrollY + iconPos.top - 60) + "px";
  mypopup.style.display = "block";
}

function hidePopup(evt) {
  mypopup.style.display = "none";
}
body {
  background-color: #33333f;
}

#mypopup {
  width: 400px;
  padding: 20px;
  font-family: Arial, sans-serif;
  font-size: 10pt;
  background-color: white;
  border-radius: 6px;
  position: absolute;
  display: none;
}

#mypopup::before {
  content: "";
  width: 12px;
  height: 12px;
  transform: rotate(45deg);
  background-color: white;
  position: absolute;
  left: -6px;
  top: 68px;
}
<svg width="400" height="400">
  <g id="myicon" pointer-events="all">
    <circle cx="100" cy="150" r="14" fill="none" stroke="gold" stroke-width="2"/>
    <circle cx="100" cy="144" r="2" fill="gold"/>
    <rect x="98.5" y="148" width="3" height="10" fill="gold"/>
  </g>
</svg>

<div id="mypopup">
  <h3>Popup title</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
  <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

【讨论】:

  • 谢谢。 getBoundingClientRect 方法正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 2013-06-11
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多