處理 DOM 元素的樣式時,常會遇到一個惱人的情況:頁面上明明寫了 CSS,用 JavaScript 去讀 elem.style 卻拿到空值。原因是樣式表(無論外部檔案還是內聯樣式)計算出來的結果,並不會反映到元素的 inline style 屬性上——style 只記錄「直接寫在該標籤 style 屬性裡」的宣告。
要拿到真正生效的樣式,需要分三層降級處理:先看 inline style,再嘗試 IE 的 currentStyle,最後使用 W3C 標準的 getComputedStyle。
完整實現如下:
<script type="text/javascript">
function getStyle( elem, name )
{
// 如果該屬性存在於 style[] 中,說明它最近被直接設置過
if (elem.style[name])
{
return elem.style[name];
}
// 否則嘗試 IE 的方式
else if (elem.currentStyle)
{
return elem.currentStyle[name];
}
// 或者 W3C 的方法
else if (document.defaultView && document.defaultView.getComputedStyle)
{
// 它使用 "text-align" 這樣的規則寫法,而不是 "textAlign"
name = name.replace(/([A-Z])/g,"-$1");
name = name.toLowerCase();
// 取得 computed style 物件並取值
var s = document.defaultView.getComputedStyle(elem,"");
return s && s.getPropertyValue(name);
}
// 其他瀏覽器
else
{
return null;
}
}
</script>
駝峰轉連字符。W3C 的 getPropertyValue 要求傳入 text-align 形式,而 JS 裡習慣寫 textAlign,所以要用正則把大寫字母轉成 -小寫。
三層降級的順序有意義。inline style 優先級最高且成本最低,因此放在最前面;currentStyle 是 IE 的私有實作;getComputedStyle 才是標準解法。
注意 computed 值與指定值的差別。getComputedStyle 回傳的是最終計算結果,例如寬度會是具體像素值而非百分比,顏色會是 rgb() 形式。這正是我們想要的效果,但也意味著別指望它告訴你作者原本寫了什麼。
封裝成一個通用函數之後,後續做主題切換、響應式測量、動畫起點計算等需求都會輕鬆很多。