DIV CSS 佈局教程網

jQuery 操作 CSS 樣式、位置與尺寸的方法總整理
編輯:JQuery特效代碼     

這份筆記把 jQuery 中處理樣式、座標與尺寸的方法整理成三大類,每個都附上返回值與可直接複製的範例,適合當速查表使用。

一、CSS 樣式

1. css(name):讀取樣式屬性

取得第一個符合元素的樣式屬性值,回傳字串。

$("p").css("color");   // 取得第一個段落的 color 屬性值

2. css(properties):批次設定多組樣式

把「名稱/值」對的物件一次套用到所有符合元素上,這是在多個元素上設定大量樣式最有效率的方式。

// 將所有段落的文字設為紅色、背景設為藍色
$("p").css({ color: "#ff0011", background: "blue" });

// 屬性名稱含 "-" 時必須用引號包起來
$("p").css({ "margin-left": "10px", "background-color": "blue" });

3. css(name, value):設定單一屬性

數值會自動轉為像素單位。

$("p").css("color", "red");   // 將所有段落文字設為紅色

二、位置

1. offset():相對視窗的偏移

回傳含 top 與 left 兩個整數屬性的物件,此方法僅對可見元素有效。

// 取得第二段的偏移
var p = $("p:last");
var offset = p.offset();
p.html("left: " + offset.left + ", top: " + offset.top);

2. position():相對父元素的偏移

回傳含 top 與 left 的物件。為了計算精準,建議在 padding、border、margin 上明確使用像素單位。同樣只對可見元素有效。

var p = $("p:first");
var position = p.position();
$("p:last").html("left: " + position.left + ", top: " + position.top);

3. scrollTop()/scrollTop(val)

取得或設定相對捲軸頂部的偏移,對可見與隱藏元素都有效。

var p = $("p:first");
$("p:last").text("scrollTop:" + p.scrollTop());

$("div.demo").scrollTop(300);   // 設定為 300

4. scrollLeft()/scrollLeft(val)

取得或設定相對捲軸左側的偏移,同樣對隱藏元素有效。

var p = $("p:first");
$("p:last").text("scrollLeft:" + p.scrollLeft());

$("div.demo").scrollLeft(300);

三、尺寸

1. height()/height(val)

取得第一個符合元素的高度值(px)。自 jQuery 1.2 起,也可用來取得 window 與 document 的高度。設定時若未明確指定單位,預設以 px 處理。

alert($("p").height());          // 取得第一段的高度
alert($(document).height());     // 取得文件高度

$("p").height(20);               // 把所有段落高度設為 20

2. width()/width(val)

alert($("p").width());           // 取得第一段的寬度

$("p").width(20);                // 把所有段落寬度設為 20

3. innerHeight()/innerWidth()

取得內部區域尺寸,包含 padding、不含 border,對可見與隱藏元素都有效。

var p = $("p:first");
$("p:last").text("innerHeight:" + p.innerHeight());
$("p:last").text("innerWidth:" + p.innerWidth());

4. outerHeight(options)/outerWidth(options)

取得外部尺寸,預設包含 padding 與 border;傳入 true 時會把 margin 也計算進去。

var p = $("p:first");
$("p:last").text("outerHeight:" + p.outerHeight() + " , outerHeight(true):" + p.outerHeight(true));
$("p:last").text("outerWidth:" + p.outerWidth() + " , outerWidth(true):" + p.outerWidth(true));

把這幾個尺寸方法的關係記牢——content 是 height(),加 padding 是 innerHeight(),再加 border 是 outerHeight(),再加 margin 才是 outerHeight(true)——排版計算時就不容易出錯。以上為個人整理,若有遺漏或錯誤歡迎指正。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved