outerHeight() 用來取得第一個符合元素外部的高度,預設會把 padding(內距)與 border(邊框)計算在內。這個方法對可見與隱藏的元素都有效,因此在計算佈局時相當實用。
它的語法為 outerHeight(options),其中 options 是個布林值,預設為 false;當設為 true 時,會連 margin(外距)一起計算進去。
HTML 程式碼:
<p>Hello</p><p>2nd Paragraph</p>
jQuery 程式碼:
var p = $("p:first");
$("p:last").text( "outerHeight:" + p.outerHeight() + " , outerHeight(true):" + p.outerHeight(true) );
結果:
<p>Hello</p><p>outerHeight: 35 , outerHeight(true):55</p>
從結果不難看出差異:不帶參數時回傳 35,代表高度含 padding 與 border;帶 true 時回傳 55,多算進了 margin。掌握這個差異,在做元素間距計算或動態佈局時就能精準抓到真正佔用的空間。