`.css()` 是 jQuery 樣式操作核心,支援獲取計算值、單一/批量設值、隱式單位補齊、CSS Hooks 自定義屬性處理。本文深度解析內部機制、常見誤區與原生替代。
// Getter
.css(propertyName) → String (computed value, first element only)
// Setter (single)
.css(propertyName, value|function(index, currentValue)) → jQuery
// Setter (multiple)
.css(propertiesObject) → jQuery
$('#el').css('width', 300); // → '300px' (自動補 px)
$('#el').css('zIndex', 10); // → '10' (無單位屬性不補)
$('#el').css('opacity', 0.5); // → '0.5'
$('#el').css('transform', 'rotate(45deg)'); // 現代屬性直接支援
內部維護 `cssNumber` 白名單 (`zIndex`, `opacity`, `fontWeight` 等) 決定是否補 `px`。
// 註冊 hook
$.cssHooks.customRotate = {
get: (elem, computed) => {
const transform = $.css(elem, 'transform');
return transform.match(/rotate\(([^)]+)\)/)?.[1] || '0deg';
},
set: (elem, value) => {
const current = $.style(elem, 'transform') || 'none';
$.style(elem, 'transform', current.replace(/rotate\([^)]+\)/, '') + ` rotate(${value})`);
}
};
// 使用如原生屬性
$('#el').css('customRotate', '45deg');
console.log($('#el').css('customRotate')); // "45deg"
| 反模式 | 問題 | 優化 |
|---|---|---|
| 迴圈中重複 `.css('prop', val)` | 每次觸發重排/重繪 | 批量物件 `.css({...})`、或切換 CSS 類別 |
| 讀寫交錯 `w = el.css('width'); el.css('height', h)` | 強制同步佈局 | 先讀取所有需求值,再一次性寫入 |
| 大量元素動畫用 `.css()` 逐幀 | JS 主執行緒阻塞、掉幀 | CSS `transition`/`animation`、Web Animations API、GSAP |
// 設定
el.style.cssText = 'width: 300px; color: red;'; // 覆寫所有內聯
Object.assign(el.style, { width: '300px', color: 'red' }); // 合併
// 獲取計算值
getComputedStyle(el).getPropertyValue('width'); // "300px"
getComputedStyle(el).width; // "300px" (屬性存取器)
// 獲取內聯樣式原始值
el.style.width; // "50%" (若為百分比)
el.getAttribute('style'); // 完整 style 字串
interface JQuery {
css(propertyName: string): string;
css(propertyName: string, value: string | number | (index: number, currentValue: string) => string | number): this;
css(properties: Record string | number>): this;
}
善用 `.css()` 便利性,但關鍵路徑、高頻動畫、大量元素操作請轉向原生 API 或 CSS 驅動方案。