如何在SVG内部悬停时获得自定义工具提示框?

时间:2017-02-24 11:02:04

标签: javascript html css 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>

1 个答案:

答案 0 :(得分:0)

放置在内联SVG上的DIV是显示与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>