element.style 只能取得行內樣式;getComputedStyle 可取得最終樣式;currentStyle 則是舊版 IE 的方案。
var div = document.getElementsByTagName("div")[0];
console.log(div.style.backgroundColor);
console.log(window.getComputedStyle(div, null).backgroundColor);
function getStyle(obj, attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
return window.getComputedStyle(obj, false)[attr];
}
若屬性名稱含連字號,可使用 getPropertyValue:
window.getComputedStyle(obj, null).getPropertyValue('background-color');
在 Firefox 3.6 存取 iframe 內樣式時,可能需要 document.defaultView.getComputedStyle。