2011-07-14 84 views

回答

6

DOM方法(如document.getElementById())創建指向幷包含有關指定HTMLElement或元素集的某些細節的對象。

不幸的是,.style屬性只知道使用該功能設置的樣式屬性。在下面的示例中,單擊what color?將不起作用,直到您點擊change color

<html> 
<head> 
<script> 
function whatColor() { 
    var d = document.getElementById('ddd'); 
    alert(d.style.backgroundColor); 
} 
function changeColor() { 
    var d = document.getElementById('ddd'); 
    d.style.backgroundColor='orange'; 
} 
</script> 
<style> 
#ddd { 
    background-color:gray; 
} 
</style> 
</head> 
<body> 
<input type="button" onclick="whatColor();" value="what color?" /> 
<input type="button" onclick="changeColor();" value="change color" /> 
<div id="ddd">&nbsp;</div> 
</body> 
</html> 

我建議你閱讀庫爾德工人黨武裝對的getComputedStyle和currentStyle(IE,當然是不同的)大頁面http://www.quirksmode.org/dom/getstyles.html

在教程結束時,有你的目的很體面的功能,雖然這樣的框架作爲jQuery提供非常方便&功能強大的功能,爲造型頁面元素:http://api.jquery.com/css/

+0

感謝您澄清.style只知道它設置的值。我認爲jquery的東西就是我一直在尋找的東西。 – ShrimpCrackers

1

它顯示動態設置的值。如果你想找到當前值,你需要計算出的值。同樣的問題被問,檢查這裏

Stackoverflow

+0

如果樣式是在外部樣式表中給出的,那麼它是否不會覆蓋默認值?我在外部CSS表單中爲我傳入的元素定義了顯示,但顯示爲未定義。 – ShrimpCrackers

+0

我的意思是,它會讀取與javascsript設置的屬性。要從樣式表中獲取值,您需要計算出的值 – Ibu

0

,如果它實際上已設置您的片段將只顯示的style.display值我的回答,不一定會顯示默認值。

1

其實這是可能的使用window.getComputedStyle(element[, pseudoElt])

該方法在應用活動樣式表並解析這些值可能包含的任何基本計算後給出元素的所有CSS屬性的值。

相關問題