如何在 SVG 中悬停时获取自定义工具提示框?

How to get custom tooltip box on hover inside SVG?

我有一张 SVG 格式的地图,其中显示了很多城市。我想做的是,每当鼠标悬停在城市上时,它都会显示一些本身应该在 HTML div.

中的细节

这是我想要的演示:http://www.nytimes.com/elections/results/senate

我不知道该怎么做,我也找不到答案。 这是 SVG 文件的示例代码:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="356 432 235 237">
  <g title="Uttar Pradesh" fill="#ccc">
    <path d="M 402.80505,648.30477 C 400.84581" fill="rgb(255,166,46)"/>
    <path d="M 402.80505,648.30477 C 400.84581" fill="rgb(255,166,46)"/>
    ...
  </g>
</svg>

A DIV 位于内联 SVG 之上,是显示与 SVG 元素相关的数据的最多样化方式。可以突出显示该元素,并且 DIV 可以包括附加到该元素的关联数据。 DIV 位于考虑到网页滚动位置的元素处。 下面是一个基本示例。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>ToolTip With DIV</title>

</head>
<body style='font-family:arial'>
<center>
<b>ToolTip With DIV</b><br /><br />
Below are 3 elements with an onmouseover event and their data attribute.<br />
<br />
<div style='width:90%;background-color:gainsboro;text-align:justify;padding:10px;border-radius:6px;'>
A DIV, that is placed over the inline SVG, is the most diversified means of showing data related to an SVG element. The element can be highlighted and the DIV can
include the associated data attached to the element. The DIV is positioned at the element taking into consideration the web page scrolled position.
</div>
<p></p>
<div id="svgDiv" style='background-color:gainsboro;width:400px;height:400px;'>
<svg id="mySVG" width="400" height="400">
<circle onmouseover=showMyTooltip(evt) cx=150 cy=150 r=60 fill=red stroke="black" stroke-width="0"  data="I am a Circle" />
<rect onmouseover=showMyTooltip(evt)  x=200 y=200 width=60 height=60 fill=lime  data="I am a Rectangle"  stroke="black" stroke-width="0"  />
<ellipse onmouseover=showMyTooltip(evt)  cx=300 cy=300 rx=60 ry=20 fill=blue data="I am an Ellipse"  stroke="black" stroke-width="0"   />
</svg>
</div>
<div id=tooltipDiv style='background:white;padding:5px;position:absolute;top:0px;left:0px;visibility:hidden'></div>

</body>
<script>

var PreviousElement
//---mouseover element--
function showMyTooltip(evt)
{
    var target = evt.target
   if(!PreviousElement||PreviousElement!=target) //--prevent 'stutter'---
   {
        if(PreviousElement) //---remove highlight (stroke) ---
            PreviousElement.setAttribute('stroke-width',0)

        target.setAttribute('stroke-width',3)
        var myData=target.getAttribute("data")

        tooltipDiv.innerHTML=myData

        var x = evt.clientX;
        var y = evt.clientY;

        var scrollX = window.pageXOffset
        var scrollY = window.pageYOffset

        var divLeft=x+5+scrollX+"px"
        var divTop=y+5+scrollY+"px"

        tooltipDiv.style.left=divLeft
        tooltipDiv.style.top=divTop
        tooltipDiv.style.visibility="visible"
        PreviousElement=target
  }
}

</script>

</html>