要精準控制元素的位置與留白,就必須搞清楚 jQuery 提供的三組尺寸方法:height()/innerHeight()/outerHeight()。本文聚焦在最外層的 outerHeight() 與 outerWidth()。
以 CSS 盒模型的順序來看:
height():只有內容高度。
innerHeight():內容 + padding。
outerHeight():內容 + padding + border。
outerHeight(true):再加上 margin。
寬度方面 width()、innerWidth()、outerWidth() 的關係完全相同。
取得第一個符合元素外部高度(預設包含 padding 與 border)。這個方法對可見與隱藏的元素都有效,這點與部分舊版 jQuery 的方法不同,實作時相當方便。
回傳值:Integer
參數:options(Boolean) — 預設 false,設為 true 時把 margin 也計入。
<p>Hello</p><p>2nd Paragraph</p>
var p = $("p:first");
$("p:last").text(
"outerHeight:" + p.outerHeight()
+ " , outerHeight(true):" + p.outerHeight(true)
);
// 結果:<p>outerHeight: 35 , outerHeight(true):55</p>
兩個數值差了 20,正是上下 margin 加總(每邊 10px)的結果。
取得第一個符合元素外部寬度(預設包含 padding 與 border)。同樣對隱藏元素有效。
回傳值:Integer
參數:options(Boolean) — 設為 true 時把 margin 計入。
var p = $("p:first");
$("p:last").text(
"outerWidth:" + p.outerWidth()
+ " , outerWidth(true):" + p.outerWidth(true)
);
// 結果:<p>outerWidth: 65 , outerWidth(true):85</p>
置中計算:彈出層要水平置中,需要知道自身寬度:
var $box = $("#dialog");
$box.css("left", ($(window).width() - $box.outerWidth()) / 2 + "px");
這裡必須用 outerWidth() 而不是 width(),因為 left 定位的是元素的邊界框,包含 border 與 padding。用錯就會偏掉幾個像素。
sticky 表頭的觸發點:判斷元素是否快捲出視窗時,要比較的是 outerHeight(true),因為 margin 也佔了版面空間。
動態計算 iframe 高度:如前所述,彈出層內的 iframe 高度常用 outerHeight() - 標題列高度 推算。
很多人以為 outerHeight(true) 會包含 outline,實際上不會——outline 不佔用版面空間,也不計入任何 jQuery 尺寸方法中。若你需要含 outline 的視覺範圍,得自己加上計算。
另外,box-sizing: border-box 會改變 width() 的意義(此時它回傳的是含 padding 與 border 的寬度),在解讀尺寸時要特別留意專案的全域樣式設定。這些方法都只接受數字, retrieved 值一律為 px 整數,若實際樣式用了 em 或 %,jQuery 會回傳換算後的像素值。