萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery css() 方法全解析:樣式獲取、設置、對象批量操作與 hover 交互

css() 方法四大重載形式

簽名用途返回值示例
.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'})

核心用法示例

1. 獲取樣式(自動處理瀏覽器差異)

// 單個獲取:返回計算後的像素值(非原始單位)
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" }

2. 設置樣式(駝峰或連字符均可)

// 單個設置
$('#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);

3. 函數值:基於當前值動態計算

// 所有匹配元素寬度 + 20px
$('.item').css('width', function (index, currentValue) {
  return parseFloat(currentValue) + 20 + 'px';
});

// 根據索引交替顏色
$('tr').css('background-color', function (i) {
  return i % 2 === 0 ? '#f9f9f9' : '#fff';
});

hover 交互的正確姿勢

誤區:用 .css() 在 hover 中切換顏色 —— 結構與行為耦合、難維護、無過渡動畫。

// ❌ 不推薦
$('#link').css('color', '#123456').hover(
  function () { $(this).css('color', '#999'); },
  function () { $(this).css('color', '#123456'); }
);

推薦:CSS 類切換 + transition

.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'); }
);

進階:hoverIntent 防抖(防止誤觸發)

// 簡易版:延遲 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
);

css() 內部機制與性能提示

  1. 獲取時觸發回流:讀取 width/height/margin/padding/top/left 等幾何屬性會強制瀏覽器回流。批量讀取時建議一次性讀完再寫入
  2. 設置時統一處理單位:數值會自動補 px(除 z-index、font-weight、opacity 等無單位屬性)
  3. CSS 變量支持:$('#box').css('--main-color', '#f00') 可動態修改 CSS 自定義屬性
  4. 避免頻繁 .css() 循環:大量元素樣式修改時,改用 .addClass() 或直接操作 `