2013-02-01 27 views
0

我試圖從一個元素中拉出CSS數據,但由於某種原因我正在打牆。我一直在盯着並試圖調整相同的代碼行一個小時,我一直未定義或NaN。使用getElementById拉CSS數據

這裏是簡寫JS:

var newVar = document.getElementById("cssItem").style.top; 

的CSS:

#cssItem { 
position: absolute; 
top:  100px; 
left:  100px; 
width:  600px; 
height:  400px; 
} 

同樣,每次登錄時newVar它回來未定義或NaN。

回答

2

Node.style只適用於內聯樣式。如果你想要得到的渲染風格,使用此:

var newVar = window.getComputedStyle(document.getElementById("cssItem")).top; 

這裏的小提琴:http://jsfiddle.net/q93B6/