2014-01-16 55 views
0

在jQuery中,你可以做如何根據文檔獲取SVG中元素的座標?

$('div').offset() 

,並返回根據該文件的一個元素的位置。

不幸的是,這不適用於SVG元素。

有沒有什麼辦法讓SVG元素的絕對位置就像正常的DOM元素一樣?

+0

jQuery的不知道,但如果一切都失敗了,你可以嘗試像一個jQuery插件SVG如http ://keith-wood.name/svg.html可以幫助訪問svg元素,或者像Raphael/Snap等其他庫(可能是你需要的矯枉過正)。 – Ian

回答

0

這可以通過使用clientX,clientY plus pageXOffset,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" 
} 
相關問題