简体   繁体   中英

How can I get the coordinates of an element inside SVG according to the document?

In jQuery you can do

$('div').offset()

and it returns the position of an element according to the document.

Unfortunately, this doesn't work with SVG elements.

Is there any way to get the absolute position of an SVG element just like it works for normal DOM elements?

This can be determened by using clientX, clientY plus pageXOffset, pageYOffset.

Try in html page:

<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>

with the code:

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"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM