萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS style 與 class 權重與加載順序深度解析

核心結論:內聯 style 權重 > class 選擇器

CSS 級聯規則中,內聯樣式(style 屬性)優先級最高(權重 1000),class 選擇器權重為 10。無論 class 定義在 style 屬性前後,內聯樣式永遠勝出——除非 class 使用 !important。

代碼驗證實驗

<html>
<head>
    <style>
        .aa {
            cursor: wait;
            color: #f00;          /* 紅色 */
        }
    </style>
    <script>
        function clickD(obj) {
            // 方式一:修改 class(無法覆蓋內聯 style)
            obj.className = "aa";
            
            // 方式二:直接修改 style(會覆蓋內聯 style)
            // obj.style.color = "#f00";
            // obj.style.cursor = "wait";
        }
    </script>
</head>
<body>
    <div onclick="clickD(this)" style="cursor: pointer; color: #000;">
        點擊試一下(初始:黑字、pointer 游標)
    </div>
</body>
</html>

執行結果分析

操作方式color 結果cursor 結果原因
點擊觸發 className = "aa"❌ 保持黑色 (#000)❌ 保持 pointer內聯 style (1000) > class (10)
點擊觸發 obj.style.color = "#f00"✅ 變紅色 (#f00)✅ 變 waitJS 修改內聯 style,同級覆蓋

CSS 優先級完整計算規則

/* 優先級權重計算:(內聯, ID, Class/屬性/偽類, 元素/偽元素) */
style=""                    → (1, 0, 0, 0) = 1000
#id                         → (0, 1, 0, 0) = 100
.class / [attr] / :hover    → (0, 0, 1, 0) = 10
div / ::before              → (0, 0, 0, 1) = 1
*                           → (0, 0, 0, 0) = 0
!important                  → 無限大(破壞結構,慎用)

常見誤區與最佳實踐

❌ 誤區:以為後寫的 class 能覆蓋前面的 style

CSS 載入順序只影響同權重選擇器。內聯 style 權重碾壓所有選擇器。

✅ 最佳實踐 1:避免內聯 style,改用 class 切換

<style>
    .default { cursor: pointer; color: #000; }
    .waiting { cursor: wait; color: #f00; }
</style>

<div class="default" onclick="this.className='waiting'">點擊試一下</div>

✅ 最佳實踐 2:必須用內聯時,用 CSS 變數保留彈性

<div style="--cursor: pointer; --color: #000; cursor: var(--cursor); color: var(--color);">
    點擊試一下
</div>

<script>
function clickD(obj) {
    obj.style.setProperty('--cursor', 'wait');
    obj.style.setProperty('--color', '#f00');
}
</script>

✅ 最佳實踐 3:JS 操作樣式優先用 classList

// 現代 API,支援增刪改查、toggle
element.classList.add('waiting');
element.classList.remove('default');
element.classList.toggle('active');
element.classList.contains('waiting'); // true/false

特殊情況:!important 逆轉

.aa {
    cursor: wait !important;    /* 強制提升權重 */
    color: #f00 !important;
}

/* 此時 className = "aa" 會覆蓋內聯 style */
/* 但會導致後續無法用 JS style 覆蓋,陷入 !important 戰爭,極不推薦 */

總結

  • 內聯 style 權重最高(1000),class 選擇器(10)無法覆蓋
  • JS 修改 element.style.xxx 修改的是內聯樣式,可覆蓋原內聯值
  • JS 修改 element.className / classList 只能在無內聯衝突時生效
  • 架構上:樣式寫在 CSS、行為寫在 JS、透過 class 切換狀態,避免直接操作 style
copyright © 萬盛學電腦網 all rights reserved