| 簽名 | 用途 | 返回值 |
|---|---|---|
| `.css(propertyName)` | 獲取**第一個**元素的計算樣式值 | String |
| `.css(propertyNames[])` | 獲取多個屬性 (jQuery 1.9+) | Object |
| `.css(propertyName, value)` | 設置**所有**匹配元素的屬性 | jQuery (鏈式) |
| `.css(propertyName, function)` | 函數值:`function(index, currentValue)` | jQuery |
| `.css(propertiesObject)` | 批量設置多屬性 | jQuery |
const color = $('p').css('color'); // "rgb(0, 0, 0)" 或 "transparent"
// ⚠️ 簡寫屬性無效:$('div').css('background') 可能返回 undefined
// ✅ 必須用長屬性:$('div').css('background-color')
$('p').css('color', 'red'); // 字串值
$('p').css('font-size', '1.2rem'); // 帶單位
$('p').css('opacity', 0.5); // 數值自動轉字串
$('p').css('transform', 'rotate(45deg)'); // 複雜值
// 逐漸增加寬度
$('div').css('width', (i, cur) => parseFloat(cur) * 1.2 + 'px');
// 交替行顏色
$('tr').css('background-color', (i, cur) => i % 2 === 0 ? '#f5f5f5' : '#fff');
$('p').css({
'color': 'white',
'background-color': '#98bf21',
'font-family': 'Arial, sans-serif',
'font-size': '20px',
'padding': '5px 10px'
});
const styles = $('div').css(['width', 'height', 'background-color', 'margin-top']);
// { width: "300px", height: "200px", background-color: "rgb(255, 255, 255)", margin-top: "10px" }
<div style="width: 50%;"></div>
$('div').css('width'); // "300px" (像素值),非 "50%"
需原始值請用 `element.style.width` 或 `getComputedStyle(el).getPropertyValue('width')`(同樣返回計算值)。
// ❌ 返回 undefined 或不完整
$('div').css('background');
$('div').css('border');
$('div').css('margin');
// ✅ 必須拆分長屬性
$('div').css('background-color');
$('div').css('border-top-width');
// ❌ 無效
$('div').css('color', 'red !important');
// ✅ 替代方案
$('div').addClass('force-red'); // CSS: .force-red { color: red !important; }
// 或
$('div')[0].style.setProperty('color', 'red', 'important');
// ❌ 迴圈中交替讀寫 → 強制重排 N 次
for (let i = 0; i < 1000; i++) {
const h = $(el).css('height'); // 讀 → 觸發重排
$(el).css('height', h + 1); // 寫
}
// ✅ 批量讀、批量寫
const heights = elements.map(el => $(el).css('height')); // 全讀
elements.forEach((el, i) => $(el).css('height', heights[i] + 1)); // 全寫
// ✅ 更好:用 CSS 類切換,或 requestAnimationFrame 批次更新
elements.forEach(el => el.classList.add('grow')); // CSS 定義 .grow { height: calc(...); }
$('.box').css('width', 100); // "100px" 自動補 px
$('.box').css('z-index', 10); // "10" 無單位
$('.box').css('opacity', 0.5); // "0.5" 無單位
// 規則:CSS 屬性為長度類且非 0 時自動加 px,其餘不加
| jQuery | 原生 DOM API |
|---|---|
| `$(el).css(prop)` | `getComputedStyle(el)[prop]` 或 `el.style[prop]` (僅內聯) |
| `$(el).css(prop, val)` | `el.style[prop] = val` |
| `$(el).css({prop:val})` | `Object.assign(el.style, {prop:val})` |
| `$(els).css(prop, fn)` | `els.forEach((el,i) => el.style[prop] = fn(i, el.style[prop]))` |
`css()` 是 jQuery 最常用的方法之一,**讀取計算樣式、批量設置、函數值動態計算** 是其三大核心場景。掌握「簡寫屬性不可讀、!important 無效、讀寫分離避免強制重排」三大鐵律,即可寫出高效能、無 Bug 的樣式操作代碼。現代專案建議優先用 CSS 類切換 + CSS 變數,僅在動態計算極其複雜時才用 JS 直接操作 `style`。