如何根据文档获取SVG中元素的坐标?

时间:2014-01-16 14:37:47

标签: javascript jquery html svg

在jQuery中你可以做到

$('div').offset()

并根据文档返回元素的位置。

不幸的是,这不适用于SVG元素。

有没有办法获得SVG元素的绝对位置,就像它适用于普通的DOM元素一样?

1 个答案:

答案 0 :(得分:0)

这可以通过 clientX,clientY plus pageYOffset,pageYOffset来确定。

尝试html页面:

<div id="svgDiv" style='width:400px;height:400px;'>
    <svg id="mySVG" width="400" height="400">
        <rect id="myRect" onmouseover="showMyComment(evt)"  onmouseout="hideMyComment()" x="100" y="100" width="100" height="100" fill="blue" />
    </svg>
</div>
<div style='position:absolute;visibility:hidden' id="myCommentDiv">This is my location</div>

代码:

function showMyComment(evt)
{
    x=evt.clientX + window.pageXOffset
    y=evt.clientY + window.pageYOffset
    myCommentDiv.style.left=x+"px"
    myCommentDiv.style.top=y+"px"
    myCommentDiv.style.visibility="visible"
}
function hideMyComment()
{
  myCommentDiv.style.visibility="hidden"
}
相关问题