| 方法 | 優先級 | 適用場景 | 優點 | 缺點 |
|---|---|---|---|---|
1. 行內樣式 element.style | 最高 (1000) | 頻繁變動的動態值(拖拽座標、動畫中間態) | 即時生效、覆蓋所有樣式表、JS 直接控制 | 結構樣式耦合、難維護、無法使用偽類/媒體查詢 |
2. 切換 class element.className / classList | 中等 (0-1-0) | 狀態切換(開關、主題、驗證狀態) | 關注點分離、可維護、支援複雜選擇器、效能佳 | 無法表達連續數值變化 |
3. 插入 <style> 標籤 | 中等 | 動態主題、用戶自定義樣式、A/B 測試 | 可生成任意 CSS 規則、作用域可控 | 插入順序影響優先級、難除錯、CSP 限制 |
4. 切換/停用 <link> 樣式表 | 依載入順序 | 主題切換、大型樣式集合切換 | 瀏覽器快取友善、關注點分離 | 閃爍風險、切換延遲、無法細粒度控制 |
element.styleconst el = document.getElementById("box");
// 正確:駝峰命名法
el.style.fontSize = "18px";
el.style.backgroundColor = "#f0f0f0";
el.style.marginTop = "16px";
el.style.transform = "translateX(100px) rotate(45deg)";
// 錯誤:CSS 連字符格式
// el.style.font-size = "18px"; // SyntaxError: Unexpected token '-'
// 批次設定(現代瀏覽器)
Object.assign(el.style, {
width: "200px",
height: "100px",
display: "flex",
alignItems: "center"
});
// 讀取計算後樣式(非行內樣式無法讀取)
console.log(el.style.fontSize); // 僅回傳行內設定值
:root { --theme-color: #3498db; --spacing: 16px; }
.card { color: var(--theme-color); padding: var(--spacing); }
// JS 動態修改主題色(影響所有使用該變數的元素)
document.documentElement.style.setProperty("--theme-color", "#e74c3c");
document.documentElement.style.setProperty("--spacing", "24px");
// 讀取計算值
getComputedStyle(el).getPropertyValue("--theme-color"); // "#e74c3c"
const el = document.querySelector(".card");
// 單一操作
el.classList.add("active", "highlight"); // 添加多個
el.classList.remove("hidden"); // 移除
el.classList.toggle("expanded"); // 切換
el.classList.toggle("loading", isLoading); // 強制狀態(第二參數)
el.classList.replace("btn-primary", "btn-secondary"); // 替換
// 檢查
el.classList.contains("active"); // true/false
el.classList.value; // 完整 class 字串 "card active highlight"
// 迭代
for (const cls of el.classList) { console.log(cls); }
// 定義狀態對應類別
const STATES = {
idle: "state-idle",
loading: "state-loading",
success: "state-success",
error: "state-error"
};
function setState(element, state) {
// 移除所有狀態類別
Object.values(STATES).forEach(cls => element.classList.remove(cls));
// 添加目標狀態
element.classList.add(STATES[state]);
}
// 使用
setState(form, "loading");
fetch("/api").then(() => setState(form, "success"))
.catch(() => setState(form, "error"));
function injectCSS(cssText, id = "dynamic-styles") {
let style = document.getElementById(id);
if (!style) {
style = document.createElement("style");
style.id = id;
document.head.appendChild(style);
}
style.textContent = cssText; // 使用 textContent 防 XSS
return style;
}
// 用法:動態主題
injectCSS(`
:root { --primary: ${userTheme.primary}; --radius: ${userTheme.radius}px; }
.btn { background: var(--primary); border-radius: var(--radius); }
`);
// 停用舊樣式表
document.querySelector('link[href*="theme-dark"]').disabled = true;
// 啟用新樣式表
document.querySelector('link[href*="theme-light"]').disabled = false;
// 或動態建立
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = "/css/theme-light.css";
document.head.appendChild(link);
function getRealStyle(element, property) {
// property 使用 CSS 連字符格式:font-size, background-color
const style = window.getComputedStyle(element);
return style.getPropertyValue(property); // 或 style[camelCase(property)]
}
// 使用範例
const box = document.querySelector(".box");
console.log(getRealStyle(box, "width")); // "300px" (含單位)
console.log(getRealStyle(box, "background-color")); // "rgb(255, 0, 0)"
console.log(getRealStyle(box, "display")); // "flex"
// 封裝通用函數
function getStyle(el, prop) {
const camel = prop.replace(/-([a-z])/g, (_, l) => l.toUpperCase());
return window.getComputedStyle(el)[camel];
}
style.display = "none"隱藏的表單欄位仍會隨表單提交,導致後端收到空值或舊值,造成驗證錯誤、資料污染。
function toggleSpouseField(show) {
const container = document.getElementById("spouse-field");
const input = container.querySelector("input");
if (show) {
// 插入到正確位置
document.getElementById("marital-status").after(container);
input.required = true;
} else {
// 移離 DOM 樹(但保留引用以便恢復)
container.remove();
input.required = false;
input.value = ""; // 清空值
}
}
// 更優雅:使用 元素
const template = document.getElementById("spouse-template");
function showSpouseField() {
const clone = template.content.cloneNode(true);
document.getElementById("marital-status").after(clone);
}
function hideSpouseField() {
const field = document.getElementById("spouse-field");
if (field) field.remove();
}
style-src 'self' 'nonce-...'element.styleJavaScript 操作 CSS 的核心原則是關注點分離:JS 負責「狀態變更」,CSS 負責「視覺表現」。現代開發應以 classList + CSS 變數為主軸,配合 @supports 特性查詢,構建強健、可維護、高效能的樣式系統。