2009-05-06 14 views
7

有最近在那裏 勝利宣佈comp.lang.javascript這個線程,但沒有代碼被張貼:如何查找HTML按鈕或圖像的座標,跨瀏覽器?

上的HTML頁面,你如何找到一個元素的左下角座標(圖像或按鈕,說) 可靠跨瀏覽器和頁面樣式?在「Ajax in Action」(我有的副本)中提倡的方法在某些情況下在IE中似乎不起作用。爲了使問題更容易,我們假設我們可以將全局文檔樣式設置爲「傳統」或「過渡」等。

請提供代碼或指向代碼的指針(一個適用於所有瀏覽器的完整函數) - 不要只是說「那很容易」,並且說明遍歷DOM的內容 - 如果我想閱讀那種的東西,我會回到comp.lang.javascript。如果這是重複的,請指責我,並指出我的解決方案 - 我確實試圖找到它。

+2

聖(* &^。我只是看着jquery解決方案:向DOM中添加一個隱藏元素,其中包含每個可能的標記,然後對幾何約定進行逆向工程。網絡真是太神奇了! – 2009-05-06 12:53:25

+1

這裏有龍 – 2009-05-07 16:38:41

回答

9

以我的經驗,唯一安全可靠的方式得到的東西像這樣的工作是使用JQuery(不用怕,它只是一個你必須包含的外部腳本文件)。然後你可以使用如下語句

$('#element').position() 

$('#element').offset() 

獲得當前的座標,它在任何工作出色,到目前爲止,我遇到所有的瀏覽器。

1

試試這個:

var elm = document.getElementById('foo'); 
var point = {x:0,y:elm.offsetHeight}; // Change to y:0 to get the top-left 

while (elm) 
{ 
    // This will get you the position relative to the absolute container, 
    // which is what you need for positioning an element within it 
    if (elm.style.position == 'absolute') 
     break; 

    point.x += elm.offsetLeft; 
    point.y += elm.offsetTop; 

    elm = elm.offsetParent; 
} 
+0

格雷格,這是什麼不工作(有時)。 – 2009-05-06 12:33:23

+0

你能舉一個它不工作的具體例子嗎? – Greg 2009-05-06 12:45:43

1

在jQuery中:

var jq = $('#yourElement'); 
var position = jq.offset(); 
alert('x: ' + position.left + ', y: ' + position.top); 

var bottomLeftPixelPosition = 
    { left: position.left, top: position.top + jq.height() - 1; }; 
2

我一直在使用它,適用於IE和Firefox。

 
var Target = document.getElementById('SomeID'); 
var Pos = findPos(Target); 

AnotherObj = document.getElementById('AnotherID'); 
AnotherObj .style.top = Pos[1] + "px"; 
AnotherObj .style.left = Pos[0] + "px"; 

//------------------------------------ 
function findPos(obj) { 
//---------------------------------------- 
    var curleft = curtop = 0; 
    if (obj.offsetParent) { 
    do { 
      curleft += obj.offsetLeft; 
      curtop += obj.offsetTop; 
    } while (obj = obj.offsetParent); 
    return [curleft,curtop]; 
    } 
} 
4

我發現這個解決方案從網上...這完全解決了我的問題。 請檢查此鏈接的來源。 http://www.quirksmode.org/js/findpos.html

/** This script finds the real position, 
* so if you resize the page and run the script again, 
* it points to the correct new position of the element. 
*/ 
function findPos(obj){ 
    var curleft = 0; 
    var curtop = 0; 

    if (obj.offsetParent) { 
     do { 
     curleft += obj.offsetLeft; 
     curtop += obj.offsetTop; 
     } while (obj = obj.offsetParent); 

     return {X:curleft,Y:curtop}; 
    } 
} 

完美的作品在Firefox,IE8,歌劇(希望別人太) 感謝那些誰分享他們的知識...... 問候,

再生不良