動態建立 <style> 元素並注入 CSS 字串,是運行時主題切換、關鍵 CSS 內聯、A/B 測試樣式的常用技巧。需處理 IE 舊版 styleSheet.cssText 與標準 appendChild(textNode) 的差異。
function injectCSS(cssText) {
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) { // IE 8-
style.styleSheet.cssText = cssText;
} else { // 標準瀏覽器
style.appendChild(document.createTextNode(cssText));
}
head.appendChild(style);
return style; // 返回元素供後續移除或修改
}
// 1. 簡單規則
injectCSS('h1 { background: red; color: white; }');
// 2. 多規則字串 (建議用模板字面值)
injectCSS(`
.theme-dark { background: #1a1a1a; color: #eee; }
.theme-dark .btn { border-color: #444; }
@media (max-width: 768px) { .theme-dark .sidebar { display: none; } }
`);
// 3. 主題切換:移除舊 style 再注入新
var currentThemeStyle = null;
function setTheme(css) {
if (currentThemeStyle) currentThemeStyle.remove();
currentThemeStyle = injectCSS(css);
}
// 直接操作 CSSRuleList,無需重建 style 元素
function updateCSSRule(selector, property, value) {
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
try {
var rules = sheet.cssRules || sheet.rules;
for (var j = 0; j < rules.length; j++) {
if (rules[j].selectorText === selector) {
rules[j].style[property] = value;
return true;
}
}
} catch (e) {
// 跨域樣式表無法存取 (CORS)
}
}
return false;
}
// 使用
updateCSSRule('.theme-dark', 'background', '#000');
<style>,非關鍵異步載入style-src,需添加 nonce 或 hash 至 style 元素link rel="preload" 載入動態注入 <style> 適合輕量級運行時樣式切換,大型應用建議採用建構時方案。