讀取元素樣式是前端最基礎也最容易出錯的操作之一。寫在標籤上的、寫在 style 標籤裡的、透過 link 引入的,三種來源的可讀取性完全不同。本文把規則講清楚。
<script type="text/javascript">
function $(obj) { return document.getElementById(obj); }
function getStyle(obj, styleName)
{
if (obj.currentStyle) // for IE
{
return obj.currentStyle[styleName];
}
else // for 標準瀏覽器
{
return document.defaultView.getComputedStyle(obj, null).getPropertyValue(styleName);
}
}
</script>
內嵌樣式(直接寫在標籤的 style 屬性上):可以透過 element.style.樣式名 取得,但樣式名稱必須用駝峰格式,例如 style.backgroundColor 而非 style.background-color。
內部樣式(寫在 head 的 style 標籤中)與外部樣式(link 引入):用 element.style.樣式名 完全讀不到,會得到空字串。必須透過 currentStyle(IE)或 getComputedStyle(標準瀏覽器)才能取得。
這個差異其實不難理解:內嵌樣式時,標籤確實帶有 style 屬性,其值是一個物件,底下有各項設定;而內部或外部樣式時,style 屬性雖然存在(型別仍是 object),但底下的具體樣式值為空,因為那些設定在樣式表中而非元素屬性上。
float 是 JavaScript 的保留字,因此不能寫 style.float。IE 用 styleFloat,標準瀏覽器用 cssFloat:
var str = $('div').style.styleFloat || $('div').style.cssFloat;
// 1. 逐項賦值
$('div').style.width = '200px';
// 2. 一次覆寫整個 cssText(會取代原有全部設定)
$('div').style.cssText = 'background:blue;color:red;font-weight:bold;';
// 3. 置換 className(等於改寫 class 屬性)
$('div2').className = 'testClassName';
這裡有個常見誤解要澄清:$('div2').width 會回傳 undefined,那是因為 DOM 元素本身沒有 width 屬性——寬度是樣式,不是元素屬性。兩者不可混為一談。
讀取 offsetWidth、offsetHeight、getComputedStyle 這類值會觸發瀏覽器重新計算布局(reflow)。在迴圈中反覆讀取同一個值,是效能問題的常見來源。正確做法是先取一次存進變數,後續重複使用。
var posElem = document.getElementById('animation');
var calcWidth = posElem.offsetWidth; // 只讀一次
posElem.style.fontSize = (calcWidth / 10) + 'px';
posElem.firstChild.style.marginLeft = (calcWidth / 20) + 'px';
posElem.style.left = (-calcWidth / 2) + 'px';
現代專案不需要自己封裝 getStyle——window.getComputedStyle(element).getPropertyValue(name) 已是所有瀏覽器的標準介面,currentStyle 只存在於 IE 舊版。而 classList API(add、remove、toggle、contains)也比直接操作 className 字串方便安全得多。