2012-04-02 43 views

回答

3

這隻會給你CSS屬性left。如果你想得到它的實際座標,使用getClientRects

var rects = document.getElementById("#myDiv").getClientRects(); //This returns a set of rectangles representing the element 
var rect = rects[0]; //There is usually only 1 rectangle 
alert(rect.left); 

請注意,您不應該使用alert進行調試。這就是console.log的用途。如果您安裝了Firebug,您可以在Chrome的控制檯或Firefox中看到輸出。 alert可能會誤導,因爲它會格式化某些內容。這也是一個更煩人的使用。

+0

偉大的工作。拯救生命! :) – 2012-04-02 15:29:56

0

大概是因爲你沒有設置style.leftstyle屬性設置CSS left屬性。

element.style直接映射到style屬性。它不會給你計算風格。

請參閱getComputedStyle。如果要查看左側位置,而不是CSS left屬性的值,請參閱offsetLeft

1

我認爲這是因爲你在CSS中設置了該值,而沒有使用內聯樣式屬性。您應該使用getComputedStyle()

+0

哇,我從來沒有聽說過。很酷。 – 2012-04-02 14:31:34