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) | ✅ 變 wait | JS 修改內聯 style,同級覆蓋 |
/* 優先級權重計算:(內聯, 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 → 無限大(破壞結構,慎用)
CSS 載入順序只影響同權重選擇器。內聯 style 權重碾壓所有選擇器。
<style>
.default { cursor: pointer; color: #000; }
.waiting { cursor: wait; color: #f00; }
</style>
<div class="default" onclick="this.className='waiting'">點擊試一下</div>
<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>
// 現代 API,支援增刪改查、toggle
element.classList.add('waiting');
element.classList.remove('default');
element.classList.toggle('active');
element.classList.contains('waiting'); // true/false
.aa {
cursor: wait !important; /* 強制提升權重 */
color: #f00 !important;
}
/* 此時 className = "aa" 會覆蓋內聯 style */
/* 但會導致後續無法用 JS style 覆蓋,陷入 !important 戰爭,極不推薦 */
style 權重最高(1000),class 選擇器(10)無法覆蓋element.style.xxx 修改的是內聯樣式,可覆蓋原內聯值element.className / classList 只能在無內聯衝突時生效