jQuery 提供統一、跨瀏覽器的 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';
});
// 單一類別
$('#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); // 依條件決定
if ($('#el').hasClass('active')) { ... }
// 等價
if ($('#el').is('.active')) { ... }
// .is() 更強大:支援任意選擇器
if ($('#el').is(':visible')) { ... }
if ($('#el').is('input[type="text"]')) { ... }
var offset = $('#el').offset(); // { top: 100, left: 200 }
// 相對於 document 左上角
// 僅對可見元素有效 (display:none 回傳 {0,0} 或 undefined)
// 設置位置 (較少用,通常用 absolute/fixed + top/left)
$('#el').offset({ top: 200, left: 300 });
var pos = $('#el').position(); // { top: 20, left: 30 }
// 相對最近的 position: relative/absolute/fixed 祖先
// 常用於:在容器內定位 tooltip、下拉選單
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);
// 獲取
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();
});
$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); // 淡化至指定透明度
$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+)
| 屬性 | 正確方法 | 錯誤方法 | 說明 |
|---|---|---|---|
| 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', '...') | 類別管理用專用方法 |
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'));
});
| 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 方法。