直接讀 element.style 只能拿到行內樣式,寫在樣式表裡的規則一律讀不到。想拿到最終生效的值,得靠 getComputedStyle,而舊版 IE 則要用它自己的 currentStyle。下面這個函式把三種情況都兜住了:
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;
}
三個分支的優先順序是有講究的:先走行內樣式,因為它優先級最高、取值也最快;接著判斷 currentStyle,這是 IE 的私有實作;最後才是標準的 getComputedStyle。都取不到就回傳 null,讓呼叫端自己決定怎麼處理。
使用時傳入元素與 CSS 屬性名即可,例如 getStyle(box, 'width')。需要注意的是,getComputedStyle 回傳的是計算後的實際像素值,例如 width: 50% 會變成具體的 px 數字,這在需要精確數值做運算時反而更方便。