如何在 SVG 元素悬停时显示工具提示 div

How to display a tooltip div when an SVG element is hovered

我需要一个内联 SVG 图表,它有一个 "more information" 图标,悬停时应该触发 "tooltip"。见附件

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

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

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

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

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

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

还要注意图标上的 pointer-events="all",这确保鼠标被视为 "over" 图标元素,即使对于具有不可见填充的位也是如此。

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>