element.currentStylewindow.getComputedStyle(element, pseudoElt)行內樣式(style 屬性)可直接用 element.style.property 取得;外部樣式表則需用上述方式。
currentStyle 反映樣式表優先順序(行內 > 樣式表 > HTML 屬性 > 瀏覽器預設)。getComputedStyle 回傳最終計算值(含繼承、預設值),單位統一為絕對單位(如 px)。function getStyle(node, property) {
// 1. 行內樣式
if (node.style[property]) return node.style[property];
// 2. IE currentStyle
if (node.currentStyle) return node.currentStyle[property];
// 3. W3C getComputedStyle
if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(node, null);
return style.getPropertyValue(property);
}
return null;
}
var div = document.getElementById('myDiv');
console.log(getStyle(div, 'width')); // 如 '200px'
console.log(getStyle(div, 'backgroundColor'));// 如 'rgb(255, 0, 0)'
現代瀏覽器皆支援 getComputedStyle,IE9+ 也已支援。若專案已棄用 IE8,可直接使用標準 API;若需支援舊版 IE,保留上述判斷邏輯即可。