萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> 資料庫綜合

jQuery css() 方法完整指南:讀寫 CSS 屬性、批量操作與效能最佳實踐

jQuery css() 方法核心語法速查

用法 語法 回傳值 說明
讀取單一屬性 .css("propertyName") String 取得第一個匹配元素的計算樣式值
設定單一屬性 .css("propertyName", "value") jQuery 為所有匹配元素設定 CSS 屬性,支援鏈式呼叫
批量設定屬性 .css({ "prop1": "val1", "prop2": "val2" }) jQuery 物件字面量語法,單次 DOM 操作完成多屬性設定
函數式設定 .css("prop", function(index, currentValue) {}) jQuery 根據索引或現值動態計算新值

實戰程式碼範例

基本讀寫操作

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery css() Demo</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    p { padding: 10px; margin: 5px 0; }
    .highlight { background: #fff3cd; border: 1px solid #ffc107; }
  </style>
</head>
<body>
  <h2>CSS 屬性讀寫示範</h2>
  <p id="p1" style="background-color: #ff6b6b; color: white">紅色背景</p>
  <p id="p2" style="background-color: #4ecdc4; color: white">青色背景</p>
  <p id="p3" style="background-color: #ffe66d; color: #333">黃色背景</p>
  <p id="p4">無內聯樣式</p>
  <button id="btnGet">讀取第一個 p 的背景色</button>
  <button id="btnSet">設定所有 p 背景為淡藍</button>
  <button id="btnBatch">批量設定多屬性</button>
  <button id="btnFunc">函數式漸層背景</button>

  <script>
  $(function() {
    // 讀取單一屬性
    $("#btnGet").click(function() {
      var bg = $("p").first().css("background-color");
      alert("第一個 <p> 的背景色:" + bg);
    });

    // 設定單一屬性
    $("#btnSet").click(function() {
      $("p").css("background-color", "#a8d0e6");
    });

    // 批量設定多屬性(推薦:單次重排/重繪)
    $("#btnBatch").click(function() {
      $("p").css({
        "background-color": "#f8f9fa",
        "color": "#343a40",
        "font-size": "1.1rem",
        "border-left": "4px solid #0d6efd"
      });
    });

    // 函數式設定:根據索引產生漸層
    $("#btnFunc").click(function() {
      $("p").css("background-color", function(i) {
        var hue = (i * 60) % 360;
        return "hsl(" + hue + ", 70%, 80%)";
      });
    });
  });
  </script>
</body>
</html>

進階應用:動態主題切換

// 主題配置物件
const themes = {
  light: {
    "--bg-primary": "#ffffff",
    "--text-primary": "#212529",
    "--accent": "#0d6efd"
  },
  dark: {
    "--bg-primary": "#121212",
    "--text-primary": "#e9ecef",
    "--accent": "#6ea8fe"
  }
};

// 切換主題函數
function applyTheme(themeName) {
  const theme = themes[themeName];
  if (!theme) return;

  // 批量設定 CSS 變數(現代瀏覽器支援)
  $(":root").css(theme);

  // 儲存偏好
  localStorage.setItem("theme", themeName);
}

// 初始化
$(function() {
  const saved = localStorage.getItem("theme") || "light";
  applyTheme(saved);
  $("#themeSwitch").on("change", function() {
    applyTheme(this.checked ? "dark" : "light");
  });
});

效能優化關鍵點

✅ 推薦做法

  • 批量設定用物件字面量:.css({prop1:val1, prop2:val2}) 只觸發一次重排/重繪
  • 讀取計算樣式用原生 API:window.getComputedStyle(el)[prop] 避免 jQuery 額外開銷
  • 複雜動畫改用 CSS Transition/Animation:GPU 加速、不阻塞主執行緒
  • CSS 變數取代動態 style:修改 :root 變數即可全域生效

❌ 避免陷阱

  • 迴圈中逐個 .css() 設定 → 大量重排重繪
  • 頻繁讀取 .css("width") 等幾何屬性 → 強制同步佈局
  • 用 jQuery 做高頻動畫(scroll、resize、mousemove 事件中)

常見單位與瀏覽器差異處理

  • 顏色值統一回傳: rgb(255, 0, 0) 而非 #ff0000 或 red
  • 尺寸單位: 回傳 px 像素值,即使原設定為 rem/em/%
  • 簡寫屬性: .css("margin") 回傳 "10px 20px 10px 20px",建議拆解讀取 marginTop 等
  • Vendor Prefix: jQuery 內部自動處理 -webkit-、-moz- 等前綴

現代替代方案對照

需求 jQuery 寫法 原生現代寫法
設定單一屬性 el.css("color", "red") el.style.color = "red"
批量設定 el.css({color:"red", fontSize:"1.2rem"}) Object.assign(el.style, {color:"red", fontSize:"1.2rem"})
讀取計算樣式 el.css("font-size") getComputedStyle(el).fontSize
切換 Class el.toggleClass("active") el.classList.toggle("active")

掌握 css() 的各種用法與效能特性,能讓您在維護既有 jQuery 專案時游刃有餘;新專案建議優先採用原生 CSS Custom Properties + Class 切換的現代模式,獲得更好效能與維護性。

copyright © 萬盛學電腦網 all rights reserved