| 簽名 | 用途 | 返回值 | 示例 |
|---|---|---|---|
.css(propertyName) | 獲取單個樣式值 | String | $('#box').css('color') |
.css(propertyNames[]) | 批量獲取多個樣式 | Object | $('#box').css(['color', 'font-size']) |
.css(propertyName, value) | 設置單個樣式 | jQuery (鏈式) | $('#box').css('color', 'red') |
.css(propertiesObject) | 批量設置樣式 | jQuery (鏈式) | $('#box').css({color:'red', 'font-size':'14px'}) |
// 單個獲取:返回計算後的像素值(非原始單位)
var color = $('#box').css('color'); // "rgb(255, 0, 0)"
var width = $('#box').css('width'); // "300px" (即使 CSS 寫 100%)
// 批量獲取(jQuery 1.9+)
var styles = $('#box').css(['color', 'font-size', 'margin-top']);
// { color: "rgb(255, 0, 0)", "font-size": "14px", "margin-top": "10px" }
// 單個設置
$('#box').css('background-color', '#f00');
$('#box').css('backgroundColor', '#f00'); // 駝峰別名
// 批量設置:對象鍵推薦加引號(含連字符時必須)
var myCss = {
'background-color': '#eee',
'width': '478px',
'margin': '10px 0 0',
'padding': '5px 10px',
'border': '1px solid #ccc'
};
$('#result').css(myCss);
// 所有匹配元素寬度 + 20px
$('.item').css('width', function (index, currentValue) {
return parseFloat(currentValue) + 20 + 'px';
});
// 根據索引交替顏色
$('tr').css('background-color', function (i) {
return i % 2 === 0 ? '#f9f9f9' : '#fff';
});
誤區:用 .css() 在 hover 中切換顏色 —— 結構與行為耦合、難維護、無過渡動畫。
// ❌ 不推薦
$('#link').css('color', '#123456').hover(
function () { $(this).css('color', '#999'); },
function () { $(this).css('color', '#123456'); }
);
.link { color: #123456; transition: color 0.3s; }
.link:hover, .link.hover { color: #999; }
// JS 僅需切換類(如需非 hover 觸發)
$('#link').hover(
function () { $(this).addClass('hover'); },
function () { $(this).removeClass('hover'); }
);
// 簡易版:延遲 200ms 進入,立即離開
$.fn.hoverDelay = function (over, out, delay) {
delay = delay || 200;
var timer;
return this.each(function () {
var $this = $(this);
$this.on('mouseenter', function () {
clearTimeout(timer);
timer = setTimeout(function () { over.call($this[0]); }, delay);
}).on('mouseleave', function () {
clearTimeout(timer);
out.call($this[0]);
});
});
};
// 使用
$('.menu-item').hoverDelay(
function () { $(this).addClass('show-sub'); },
function () { $(this).removeClass('show-sub'); },
300
);
width/height/margin/padding/top/left 等幾何屬性會強制瀏覽器回流。批量讀取時建議一次性讀完再寫入px(除 z-index、font-weight、opacity 等無單位屬性)$('#box').css('--main-color', '#f00') 可動態修改 CSS 自定義屬性.addClass() 或直接操作 `