萬盛學電腦網

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

jQuery css() 方法深度解析:獲取計算值、批量設值、CSS Hooks 擴展、效能優化

`.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

獲取計算值細節

  • 回傳 `getComputedStyle` 解析後的**已計算值**,單位通常為 `px`、`rgb()`。
  • 簡寫屬性 (`margin`, `border`, `background`) **不可獲取**,需拆分長屬性 (`marginTop`, `borderLeftWidth`)。
  • 不可見元素 (`display:none`) 寬高為 `0`,需暫時顯示測量或用 `getBoundingClientRect()`。
  • 多元素集合:只回傳**第一個**元素的值。

設值自動單位補齊


$('#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`。

CSS Hooks:擴展自定義屬性


// 註冊 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 字串

TypeScript 型別擴充

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 驅動方案。

copyright © 萬盛學電腦網 all rights reserved