2013-12-19 522 views
1

我有一個關於通過javascript獲取DOM樣式的問題。獲取樣式的屬性

#quicklink { 
    position: absolute; 
    top: 500px; 
    left: 500px; 
} 

<div id="quicklink" class="draggable"> 
    <img class="menu_icon" src="4a.png" src="" />     
</div> 

當我嘗試通過此代碼獲取元素的頂部。爲什麼它總是有空字符串值?

var quicklink = document.getElementById('quicklink'); 
console.log(quicklink.style.top); // string value ??? 

謝謝!

+0

的可能重複(HTTP [如何檢索在JavaScript風格的價值?]://計算器.com/questions/2664045/how-to-retrieve-a-styles-value-in-javascript) –

回答

5

這是因爲造型不會在DOM作爲居住的那個元素的ID屬性。您可以嘗試getComputeStyle()訪問通過單獨的CSS應用的樣式。

var elem1 = document.getElementById("elemId"); 
var style = window.getComputedStyle(elem1, null); 

MDN:https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle

W3C:http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-OverrideAndComputed-h3

+0

你能向我解釋爲什麼它總是以空字符串值記錄嗎? – PhuongTT

+0

將規範文檔說明附加到我的答案中。 –

+1

該文檔解釋了getComputedStyle()在應用活動樣式表並解析這些值可能包含的任何基本計算後給出元素的所有CSS屬性的值。那麼可能這可能是之前沒有應用活動樣式表的空串的原因。 – KunJ

2

試試這個

function getCssProperty(elmId, property){ 
    var elem = document.getElementById(elmId); 
    return window.getComputedStyle(elem,null).getPropertyValue(property); 
} 
// You could now get your value like 
var top = getCssProperty("quicklink", "top"); 
console.log(top) 

DEMO

+0

你能向我解釋爲什麼它總是以空字符串值記錄嗎? – PhuongTT

1

試試這個:

var element = document.getElementById('quicklink'), 
    style = window.getComputedStyle(element), 
    top = style.getPropertyValue('top');