想讀出元素實際套用的 CSS 值,不能只用 element.style——它只看得到行內樣式,外部樣式表定義的規則完全讀不到。
IE 使用 element.currentStyle,符合 W3C 標準的瀏覽器(Firefox、Chrome、Opera、Safari)則使用 window.getComputedStyle(element, pseudoElt)。
currentStyle 物件回傳的是元素上完整的樣式表結果,而 style 物件只回傳透過 style 屬性寫入的內嵌樣式。舉例來說,若段落的 color 是靠連結式或嵌入樣式表設為 red,那麼 obj.currentStyle.color 能正確回傳 red,obj.style.color 則是空的;只有在使用者另外寫了行內樣式時,兩者才會一致。
currentStyle 反映了樣式的優先順序,在 HTML 中依序為:
1)行內樣式
2)樣式表規則
3)HTML 標籤屬性
4)HTML 標籤的內部預設定義
window.getComputedStyle(element, pseudoElt) 中,element 是必選的 HTML 元素;pseudoElt 則用來指定要取哪個偽類的樣式,一般情況傳 null 即可。
function getStyle(node, property){
if (node.style[property]) {
return node.style[property];
}
else if (node.currentStyle) {
return node.currentStyle[property];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(node, null);
return style.getPropertyValue(property);
}
return null;
}
三層判斷依序是:先看行內樣式、再看 IE 的 currentStyle、最後走標準的 getComputedStyle。這樣寫就能在各種瀏覽器上穩定取到值。