萬盛學電腦網

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

jQuery css() 方法完整指南:樣式讀寫、鏈式調用、多屬性設置、單位處理實戰詳解

css() 核心 API 速查

呼叫形式用途返回值範例
.css(propertyName)讀取單一樣式字串 (計算值)$('#box').css('width') → "300px"
.css(propertyNames[])讀取多個樣式物件 {prop: value}$('#box').css(['width','height'])
.css(prop, value)設置單一樣式jQuery 物件$('#box').css('color', 'red')
.css(object)批量設置 (JSON)jQuery 物件$('#box').css({color:'red', 'font-size':'16px'})
.css(prop, fn)函數動態設置jQuery 物件$('#box').css('width', i => (i+1)*100+'px')

完整互動範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jQuery css() 方法示範</title>
  <style>
    .container { max-width: 700px; margin: 40px auto; padding: 20px; font-family: sans-serif; }
    .box { width: 200px; height: 100px; border: 2px solid #1976d2; border-radius: 8px; margin: 15px auto; display: flex; align-items: center; justify-content: center; font-weight: bold; color: #1976d2; background: #e3f2fd; transition: all 0.3s ease; }
    .controls { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin: 20px 0; }
    button { padding: 10px 16px; background: #1976d2; color: white; border: none; border-radius: 6px; cursor: pointer; }
    button.secondary { background: #757575; }
    button.success { background: #4caf50; }
    button.danger { background: #e53935; }
    .log { background: #263238; color: #aed581; padding: 12px; border-radius: 4px; font-family: monospace; font-size: 13px; min-height: 100px; white-space: pre-wrap; }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="container">
    <h2 style="text-align:center;">jQuery css() 互動示範</h2>
    <div id="box1" class="box">Box 1</div>
    <div id="box2" class="box">Box 2</div>
    
    <div class="controls">
      <button id="btnRead">1. 讀取樣式</button>
      <button id="btnReadMulti" class="secondary">2. 批量讀取</button>
      <button id="btnSetSingle">3. 單個設置</button>
      <button id="btnSetMulti" class="success">4. JSON 批量設置</button>
      <button id="btnChain">5. 鏈式調用</button>
      <button id="btnFunc" class="secondary">6. 函數動態設置</button>
      <button id="btnReset" class="danger">重置</button>
    </div>
    <div class="log" id="log">操作日誌...</div>
  </div>

  <script>
  $(function() {
    const $boxes = $('.box');
    const $log = $('#log');
    const log = (msg) => $log.prepend(`[${new Date().toLocaleTimeString()}] ${msg}\n`);

    // 1. 讀取單一樣式 (只讀第一個元素)
    $('#btnRead').on('click', () => {
      const width = $boxes.css('width');
      const bgColor = $boxes.css('background-color');
      log(`讀取: width="${width}", background-color="${bgColor}"`);
      log(`注意: .css() 讀取只返回第一個元素的計算值`);
    });

    // 2. 批量讀取 (返回物件)
    $('#btnReadMulti').on('click', () => {
      const styles = $boxes.css(['width', 'height', 'background-color', 'border-radius', 'color']);
      log('批量讀取結果:');
      log(JSON.stringify(styles, null, 2));
    });

    // 3. 單個設置
    $('#btnSetSingle').on('click', () => {
      $boxes.css('background-color', '#fff3e0').css('color', '#e65100');
      log('單個設置: background-color, color');
    });

    // 4. JSON 批量設置 (推薦)
    $('#btnSetMulti').on('click', () => {
      $boxes.css({
        'width': '300px',
        'height': '150px',
        'background-color': '#e8f5e9',
        'color': '#2e7d32',
        'border-radius': '16px',
        'font-size': '20px',
        'border-color': '#4caf50'
      });
      log('JSON 批量設置 7 個樣式屬性');
    });

    // 5. 鏈式調用
    $('#btnChain').on('click', () => {
      $boxes
        .css('width', '250px')
        .css('height', '120px')
        .css('background', 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)')
        .css('color', 'white')
        .css('border', 'none')
        .css('transform', 'rotate(2deg)');
      log('鏈式調用 6 次 css()');
    });

    // 6. 函數動態設置 (根據索引)
    $('#btnFunc').on('click', () => {
      $boxes.css('width', (i) => (200 + i * 100) + 'px')
            .css('background-color', (i) => i === 0 ? '#ffcdd2' : '#c8e6c9');
      log('函數動態設置: 不同索引不同寬度/顏色');
    });

    // 重置
    $('#btnReset').on('click', () => {
      $boxes.attr('style', ''); // 清除所有內聯樣式
      log('已重置 (清除 style 屬性)');
    });
  });
  </script>
</body>
</html>

關鍵細節深度解析

1. 讀取返回「計算值」,非指定值

<div id="box" style="width: 50%"></div>
$('#box').css('width'); // "300px" (假設容器寬 600px),而非 "50%"

瀏覽器返回經過計算的像素值,包含單位。

2. 屬性名:駝峰式 vs 連字號

// 兩種寫法皆可,jQuery 內部自動轉換
$el.css('backgroundColor', 'red'); // 駝峰式 (JS 風格)
$el.css('background-color', 'red'); // 連字號 (CSS 颎格) ✅ 推薦,與 CSS 一致

// 批量設置時建議用連字號 (JSON 鍵名需加引號)
$el.css({
  'background-color': 'red',
  'font-size': '16px',
  'border-radius': '8px'
});

3. 自動單位處理:數值自動加 "px"

$el.css('width', 300);     // 自動變 "300px"
$el.css('width', '300');   // 字串也自動加 "px" (大多數屬性)
$el.css('width', '300px'); // 顯式指定
$el.css('zIndex', 10);     // 無單位屬性 (zIndex, opacity, lineHeight 等) 不加 px
$el.css('opacity', 0.5);   // 無單位

自動加 px 的屬性:width, height, top, left, margin, padding, font-size, border-width 等長度類屬性。

4. 鏈式調用 vs JSON 批量設置效能

// 鏈式:每次調用觸發一次樣式重計算 (較慢)
$el.css('a', 1).css('b', 2).css('c', 3);

// JSON 批量:單次重計算 (推薦)
$el.css({a:1, b:2, c:3});

5. 讀取多個樣式 (jQuery 1.9+)

const styles = $el.css(['width', 'height', 'background-color']);
// 返回: {width: "300px", height: "200px", "background-color": "rgb(255, 0, 0)"}

6. !important 無法透過 .css() 設置

// ❌ 無效
$el.css('color', 'red !important');

// ✅ 替代方案
$el.addClass('force-red'); // CSS: .force-red { color: red !important; }
// 或直接操作 style 屬性 (不推薦)
$el[0].style.setProperty('color', 'red', 'important');

實戰模式:動態主題切換

const themes = {
  light: { '--bg': '#fff', '--text': '#333', '--primary': '#1976d2' },
  dark:  { '--bg': '#121212', '--text': '#fff', '--primary': '#90caf9' }
};

function applyTheme(name) {
  const vars = themes[name];
  Object.entries(vars).forEach(([key, val]) => {
    document.documentElement.style.setProperty(key, val);
  });
  localStorage.setItem('theme', name);
}

// 初始化
applyTheme(localStorage.getItem('theme') || 'light');

避坑指南

⚠ 常見錯誤:
  • .css('width', '100%') 在某些情況下不生效 → 確保父元素有明確寬度
  • 讀取 background-color 返回 rgb(...) 或 rgba(...),非十六進制 → 比較時需統一格式
  • .css('transform') 返回 matrix(...) 矩陣字串,難以解析 → 用 CSS 類別控制動畫
  • 隱藏元素 display:none 讀取尺寸為 0 → 需先顯示再讀取,或用 .show().css('width').hide()

總結

  • 讀取:單一用 .css('prop'),多個用 .css(['prop1','prop2']),只取第一個元素
  • 設置:單一 .css('prop', val),批量 優先用 JSON .css({...}),鏈式次之
  • 單位:數值自動加 px,無單位屬性 (opacity, zIndex) 不加
  • 屬性名:建議統一用連字號 'font-size' (JSON 鍵名加引號)
  • !important:不可直接設置,改用 CSS 類別或 style.setProperty
copyright © 萬盛學電腦網 all rights reserved