萬盛學電腦網

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

jQuery CSS 操作完全指南:樣式讀寫、類別切換、座標計算與動畫控制

jQuery CSS 模組核心 API

jQuery 提供統一、跨瀏覽器的 CSS 操作介面,涵蓋內聯樣式、類別管理、幾何屬性、滾動位置、顯示/隱藏動畫。

1. 內聯樣式操作:.css()

獲取單一樣式值

var color = $('div').css('color');           // "rgb(0, 0, 0)" - 回傳計算值
var fontSize = $('div').css('font-size');    // "16px" - 含單位
var margin = $('div').css('margin');         // 簡寫屬性回傳綜合值 (不建議用於獲取)

設置單一樣式

$('div').css('color', 'red');
$('div').css('font-size', '18px');
$('div').css('margin-left', '20px');

批量設置 (物件語法,推薦)

$('div').css({
  'font-size': '16px',
  'color': '#333',
  'background-color': '#f5f5f5',
  'padding': '10px 20px',
  'border-radius': '4px'
});

函式值 (動態計算)

// 根據索引漸變顏色
$('li').css('background-color', function(index) {
  var hue = (index * 30) % 360;
  return 'hsl(' + hue + ', 70%, 80%)';
});

// 根據現有值計算新值
$('div').css('width', function(i, current) {
  return parseInt(current) + 50 + 'px';
});

重要特性

  • 自動處理瀏覽器前綴:`user-select` → `-webkit-user-select`, `-moz-user-select`, `-ms-user-select`
  • 單位自動補齊:數值型屬性 (width, height, margin, padding, top, left...) 可傳數字,自動加 `px`
  • 獲取的是計算值:非原始設定值 (如 `%`、`em`、`auto` 會轉為像素值)
  • 不支援 !important:需用 `.attr('style', 'color:red!important')` 或原生 `style.setProperty()`

2. 類別操作

.addClass() / .removeClass() / .toggleClass()

// 單一類別
$('#el').addClass('active');
$('#el').removeClass('active');
$('#el').toggleClass('active');  // 切換

// 多個類別 (空格分隔或陣列)
$('#el').addClass('active highlight');
$('#el').removeClass('active highlight');
$('#el').toggleClass('active highlight');

// 函式動態決定
$('#el').addClass(function(index, currentClass) {
  return 'item-' + index + (currentClass ? ' ' + currentClass : '');
});

// 切換並指定狀態 (強制添加/移除)
$('#el').toggleClass('active', true);   // 等同 addClass
$('#el').toggleClass('active', false);  // 等同 removeClass
$('#el').toggleClass('active', condition);  // 依條件決定

.hasClass() / .is()

if ($('#el').hasClass('active')) { ... }
// 等價
if ($('#el').is('.active')) { ... }

// .is() 更強大:支援任意選擇器
if ($('#el').is(':visible')) { ... }
if ($('#el').is('input[type="text"]')) { ... }

3. 幾何與座標

.offset() - 文檔座標

var offset = $('#el').offset();  // { top: 100, left: 200 }
// 相對於 document 左上角
// 僅對可見元素有效 (display:none 回傳 {0,0} 或 undefined)

// 設置位置 (較少用,通常用 absolute/fixed + top/left)
$('#el').offset({ top: 200, left: 300 });

.position() - 相對定位父座標

var pos = $('#el').position();  // { top: 20, left: 30 }
// 相對最近的 position: relative/absolute/fixed 祖先
// 常用於:在容器內定位 tooltip、下拉選單

.width() / .height() / .innerWidth() / .innerHeight() / .outerWidth() / .outerHeight()

var $el = $('#box');  // 假設: width:200, padding:10, border:5, margin:15

$el.width();        // 200 (content)
$el.innerWidth();   // 220 (content + padding)
$el.outerWidth();   // 230 (content + padding + border)
$el.outerWidth(true); // 260 (content + padding + border + margin)

// 同理 height 系列
// 設置寬高
$el.width(300);
$el.height(200);

4. 滾動位置

// 獲取
var scrollTop = $(window).scrollTop();   // 或 $('html, body').scrollTop()
var scrollLeft = $(window).scrollLeft();

// 設置 (瞬間跳轉)
$(window).scrollTop(500);
$('div.scrollable').scrollLeft(200);

// 動畫滾動
$('html, body').animate({ scrollTop: $('#target').offset().top }, 500);

// 滾動事件
$(window).on('scroll', function() {
  var st = $(this).scrollTop();
  if (st > 100) $('#backToTop').fadeIn(); else $('#backToTop').fadeOut();
});

5. 顯示/隱藏與動畫

基本切換

$el.show();       // display: block/inline (恢復原有 display)
$el.hide();       // display: none
$el.toggle();     // 切換

// 速度控制
$el.show(300);    // 300ms 淡入+展開
$el.hide('fast'); // 200ms
$el.toggle('slow'); // 600ms

滑動動畫 (垂直)

$el.slideDown(400);   // 高度從 0 增至原高
$el.slideUp(400);     // 高度從原高減至 0
$el.slideToggle(400); // 切換

淡入淡出 (透明度)

$el.fadeIn(400);      // opacity 0→1
$el.fadeOut(400);     // opacity 1→0
$el.fadeToggle(400);
$el.fadeTo(400, 0.5); // 淡化至指定透明度

自訂動畫 .animate()

$el.animate({
  opacity: 0.5,
  left: '+=50',
  height: 'toggle'
}, {
  duration: 500,
  easing: 'swing',  // 或 'linear', 依賴 jQuery UI/easing plugin
  complete: function() { console.log('動畫完成'); },
  step: function(now, fx) { /* 每幀回調 */ },
  queue: true       // 是否進入動畫隊列
});

// 停止動畫
$el.stop();              // 停止當前動畫
$el.stop(true);          // 清空隊列、停止當前
$el.stop(true, true);    // 清空隊列、跳至當前動畫結束狀態
$el.finish();            // 立即完成所有排隊動畫 (jQuery 1.9+)

6. 表單屬性操作 (attr vs prop)

屬性正確方法錯誤方法說明
disabled.prop('disabled', true).attr('disabled', 'disabled')布林屬性用 prop
checked.prop('checked', true).attr('checked', 'checked')布林屬性用 prop
readonly.prop('readonly', true).attr('readonly', 'readonly')布林屬性用 prop
selected.prop('selected', true).attr('selected', 'selected')option 元素用 prop
value.val('text').attr('value', 'text')表單值用 val()
href/src.attr('href', '...').prop('href', '...')HTML 屬性用 attr (prop 回傳解析後完整 URL)
class.addClass/.removeClass.attr('class', '...')類別管理用專用方法

7. 實戰:可拖曳 Modal 定位

function centerModal($modal) {
  var winW = $(window).width();
  var winH = $(window).height();
  var modW = $modal.outerWidth();
  var modH = $modal.outerHeight();
  
  $modal.css({
    left: (winW - modW) / 2 + $(window).scrollLeft(),
    top: (winH - modH) / 2 + $(window).scrollTop()
  });
}

$(window).on('resize scroll', function() {
  centerModal($('#myModal'));
});

效能建議

  • 批量讀寫分離:先讀取所有需要的值,再一次性寫入,避免佈局抖動
  • 使用 CSS 類別切換:而非逐個 `.css()` 設定,瀏覽器優化類別變更
  • 動畫用 transform/opacity:不觸發重排,GPU 加速
  • 快取 jQuery 物件:`var $el = $('#el');` 避免重複選擇
  • 大量元素操作用原生:`document.getElementById`、批量 `classList` 操作

現代原生替代方案

jQuery原生 (現代瀏覽器)
$(el).css('color', 'red')el.style.color = 'red'
$(el).addClass('active')el.classList.add('active')
$(el).hasClass('active')el.classList.contains('active')
$(el).toggleClass('active')el.classList.toggle('active')
$(el).offset()el.getBoundingClientRect() + scrollX/Y
$(el).position()el.offsetTop/Left (相對 offsetParent)
$(el).width()el.clientWidth (含 padding) / el.offsetWidth (含 border)
$(window).scrollTop()window.scrollY / document.documentElement.scrollTop
$(el).animate({opacity:0}, 300)el.animate({opacity: [1,0]}, {duration:300, easing:'ease'})
$(el).fadeIn()CSS transition + class 切換

總結

jQuery CSS 模組提供了極其便利的跨瀏覽器抽象層。核心掌握:.css() 內聯樣式、.addClass() 類別管理、.offset()/.position() 座標系統、.animate() 動畫隊列。現代開發中,靜態樣式用 CSS 類別、動態狀態用 CSS Custom Properties + class 切換、複雜動畫用 Web Animations API 或 CSS Transitions,只在需要精細控制、跨瀏覽器相容、或維護舊專案時使用 jQuery CSS 方法。

copyright © 萬盛學電腦網 all rights reserved