給元素設定多個樣式,最直白的寫法是一條一條來:
var head = document.getElementById("head");
head.style.width = "200px";
head.style.height = "70px";
head.style.display = "block";
寫起來囉嗦。想省點力氣,通常會包一個工具函式:
function setStyle(obj, css) {
for (var atr in css) {
obj.style[atr] = css[atr];
}
}
var head = document.getElementById("head");
setStyle(head, {width: "200px", height: "70px", display: "block"});
讀 Google API 的程式碼時發現它們用了 cssText,實測各瀏覽器都支援:
var head = document.getElementById("head");
head.style.cssText = "width:200px;height:70px;display:block";
和 innerHTML 一樣,cssText 簡潔、通用,而且批量操作樣式時只需要一次 reflow,對頁面渲染效能有正面幫助。
這是最容易受傷的地方。假設原本的樣式是:
<div style="color:red;">TEST</div>
你想再補一個寬度:
div.style.cssText = "width:200px;";
寬度確實套上了,但原本的 color:red 被整批清掉了。所以使用 cssText 時應該採疊加寫法,先讀舊值再拼接:
function setStyle(el, strCss) {
var sty = el.style;
sty.cssText = sty.cssText + strCss;
}
這個寫法在 IE9 / Firefox / Safari / Chrome / Opera 上沒問題,但 IE6/7/8 的 cssText 回傳值末尾缺少分號,拼接後會讓兩條宣告黏在一起而失效。因此得先補上:
function setStyle(el, strCss) {
function endsWith(str, suffix) {
var l = str.length - suffix.length;
return l >= 0 && str.indexOf(suffix, l) == l;
}
var sty = el.style,
cssText = sty.cssText;
if (!endsWith(cssText, ';')) {
cssText += ';';
}
sty.cssText = cssText + strCss;
}
相關規範可參考:
今天的專案大概不需要再為舊 IE 寫這層补丁了,但「cssText 是覆寫」這件事仍然值得牢記——即使在新瀏覽器上,用 el.style.cssText = ... 抹掉別人設定的行內樣式,也是常見的 bug 來源。若目的只是「新增一項樣式」,直接 el.style.setProperty(name, value) 或 el.style[name] = value 永遠比覆寫 cssText 安全。