`.css()` 是 jQuery 操作樣式的核心方法,支援單一/批量設值、獲取計算後值、自動單位補齊、CSS Hooks 擴展。本文涵蓋所有用法、常見坑點與原生替代方案。
// 獲取單一屬性 (回傳計算值,含單位)
$('#box').css('width'); // "300px"
$('#box').css('background-color'); // "rgb(255, 0, 0)"
// 設定單一屬性
$('#box').css('width', '400px');
$('#box').css('width', 400); // 數字自動補 'px' (部分屬性除外)
// 批量設定 (物件字面量)
$('#box').css({
width: '50%',
height: 200,
'background-color': '#f00',
marginTop: 10 // 駝峰或連字號皆可
});
// 回調函式設定 (根據索引/舊值動態計算)
$('li').css('color', (i, val) => i % 2 ? 'red' : 'blue');
$.cssHooks['rotate'] = {
get: (elem, computed, extra) => $.css(elem, 'transform').match(/rotate\(([^)]+)\)/)?.[1] || '0deg',
set: (elem, value) => {
const current = $.css(elem, 'transform') || 'none';
elem.style.transform = current.replace(/rotate\([^)]+\)/, '') + ` rotate(${value})`;
}
};
$('#box').css('rotate', '45deg'); // 如原生屬性般操作
| 問題 | 原因 | 解決 |
|---|---|---|
| 設定 `width: '50%'` 獲取卻是 `'300px'` | 回傳計算值 | 需獲取原始值用 `style.width` 或 `attr('style')` 解析 |
| 批量設定無效 | 屬性名需駝峰或加引號 | `marginTop` 或 `'margin-top'` |
| 大量元素迴圈 `.css()` 極慢 | 每次觸發重排/重繪 | 改用 CSS 類別切換、或 `DocumentFragment` 批量構建 |
| `!important` 無法透過 `.css()` 設定 | API 限制 | 用 `.css('cssText', 'color:red!important;')` 或切換類別 |