動態注入樣式在元件化開發、主題切換、第三方腳本擴充時都很常見。以下提供由簡到穩的兩種寫法。
document.createStyleSheet().cssText =
'標籤{color:red;' +
'width:300px;height:150px}' +
'.類名{……}' +
'#ID們{……}';
一行搞定。字串中的註解只是為了說明結構,實際寫入時不會被當成註解保留。
如果同一段初始化程式可能被執行多次,就會產生多個內容相同的樣式表。解法是給樣式表一個 id,建立前先檢查是否已存在:
if (!document.getElementById('theforever')) {
var ss = document.createStyleSheet();
ss.owningElement.id = 'theforever'; // 標記這張樣式表
ss.cssText =
'標籤{display:inline-block;overflow:hidden;' +
'text-align:left;width:300px;height:150px}' +
'.類名{……}' +
'#ID們{……}';
}
createStyleSheet() 早期是 IE 專屬,標準瀏覽器需改用 <style> 元素搭配 document.head.appendChild():
function injectCSS(id, css) {
if (document.getElementById(id)) { return; } // 避免重複注入
var style = document.createElement('style');
style.id = id;
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css; // 舊版 IE
} else {
style.appendChild(document.createTextNode(css));
}
(document.head || document.getElementsByTagName('head')[0]).appendChild(style);
}
injectCSS('theforever', '.box{display:inline-block;width:300px;height:150px}');
這版本同時解決了兩件事:跨瀏覽器相容,以及重複注入的問題。若你只想動態改寫既有規則而不新增整張表,則可搭配 document.styleSheets[n].cssRules 定位後修改單一屬性,效果更精準。