適用於:預定義好多套樣式,需整體切換風格時。
// HTML
內容
// JS
const el = document.getElementById('box');
// 替換所有類
el.className = 'highlight';
// 現代 classList API(推薦)
el.classList.add('highlight');
el.classList.remove('normal');
el.classList.toggle('active'); // 切換
el.classList.contains('error'); // 檢查
el.classList.replace('old', 'new'); // 替換
適用於:動態計算值、微調單一屬性、動畫中間幀。
const el = document.getElementById('box');
// 單屬性修改
el.style.color = 'red';
el.style.fontSize = '20px'; // 駝峰命名
el.style.backgroundColor = '#fff';
el.style.cssText = 'color: red; font-size: 20px;'; // 批量設置(會覆蓋原有行內樣式)
// 獲取計算後樣式(含 CSS 文件定義)
const computed = window.getComputedStyle(el);
console.log(computed.color); // rgb(255, 0, 0)
console.log(computed.getPropertyValue('font-size')); // 20px
| CSS 屬性 | JS 屬性 | 規則 |
|---|---|---|
| background-color | backgroundColor | 連字符後字母大寫 |
| font-size | fontSize | 同上 |
| z-index | zIndex | 同上 |
| float | cssFloat / styleFloat(IE) | 保留字特殊處理 |
| --custom-prop | 無直接映射 | 用 style.setProperty() |
:root {
--primary-color: #2196f3;
--spacing: 16px;
}
.box {
color: var(--primary-color);
padding: var(--spacing);
}
// JS 修改 CSS 變量(影響所有使用該變量的元素)
document.documentElement.style.setProperty('--primary-color', '#e91e63');
document.documentElement.style.setProperty('--spacing', '24px');
// 單元素覆蓋
el.style.setProperty('--primary-color', '#4caf50');
// ❌ 觸發 3 次重排
el.style.left = '10px';
el.style.top = '20px';
el.style.width = '100px';
// ✅ 批量寫入(現代瀏覽器會合併,但習慣更好)
el.style.cssText = 'left:10px; top:20px; width:100px;';
// ✅ 或使用 class
el.className = 'positioned-box';
$('#box').addClass('highlight').removeClass('normal');
$('#box').css({ color: 'red', fontSize: '20px' });
$('#box').css('color'); // 獲取計算值