透過 element.style 改樣式時,有幾個和 CSS 原始寫法不一致的地方,很容易出錯。
style 物件上的屬性名稱與 CSS 屬性幾乎一一對應,但凡含連字號的都改成駝峰寫法:
font-size → fontSize margin-top → marginTop background-color → backgroundColor
float 在 JavaScript 中是保留關鍵字,所以不能用 style.float。標準寫法是 style.cssFloat,而舊版 IE 用的是 style.styleFloat:
if (typeof elem.style.cssFloat !== 'undefined') {
elem.style.cssFloat = 'left';
} else {
elem.style.styleFloat = 'left';
}
寫入用 style,但讀取「實際生效的樣式」必須用 computed style——因為 elem.style 只包含行內樣式,讀不到樣式表裡的規則。W3C 標準環境:
var heading = document.getElementById("heading");
var computedStyle = document.defaultView.getComputedStyle(heading, null);
var computedFontFamily = computedStyle.fontFamily; // sans-serif
IE 用的是 currentStyle:
var computedFontFamily = heading.currentStyle.fontFamily;
合成一個跨瀏覽器函式:
function retrieveComputedStyle(element, styleProperty) {
var computedStyle = null;
if (typeof element.currentStyle != "undefined") {
computedStyle = element.currentStyle;
} else {
computedStyle = document.defaultView.getComputedStyle(element, null);
}
return computedStyle[styleProperty];
}
要注意兩者的差異不只是名稱:getComputedStyle 回傳的是經過層級與計算後的最終值(例如 width 會是像素值),而 currentStyle 有時回傳的是尚未計算的宣告值。依賴這個差異的程式碼在跨瀏覽器時容易出錯。
常見對應如下:
background-attachment → backgroundAttachmentborder-bottom-width → borderBottomWidthfont-family / font-size → fontFamily / fontSizeletter-spacing / line-height → letterSpacing / lineHeightlist-style-type → listStyleTypepage-break-after → pageBreakAftertext-align / text-indent → textAlign / textIndentvertical-align → verticalAlignz-index → zIndexInternet Explorer:document.all.div_id.style.JS_property = "value";
較舊的 Netscape 4.x:document.div_id.JS_property = "value";
Netscape 6+、Opera 與其他 Mozilla 系:document.getElementById(div_id).style.JS_property = "value";
最後一個實務建議:能用 class 切換解決的就不要逐屬性寫 JS。把 elem.style.cssText = '...' 換成 elem.className = 'active',樣式與行為分離之後,維護成本會低很多,也避開了上面所有名稱轉換的坑。