.outerHeight()


取得與匹配元素集合中第一個元素相關的目前運算外層高度(包含內距、邊框,以及選擇性的外距),或設定每個匹配元素的外層高度。

.outerHeight( [includeMargin ] )傳回: 數字

說明: 取得與匹配元素集合中第一個元素相關的目前運算外層高度(包含內距、邊框,以及選擇性的外距)。

傳回元素的高度,包含頂部和底部內距、邊框,以及選擇性的外距,單位為像素。如果呼叫時元素集合為空,則傳回 undefined(jQuery 3.0 之前的版本為 null)。

此方法不適用於 windowdocument 物件;對於這些物件,請改用 .height()。雖然 .outerHeight() 可用於表格元素,但對於使用 border-collapse: collapse CSS 屬性的表格,它可能會產生意外的結果。

圖 1 - 測量高度的說明

其他注意事項

  • 在某些情況下,由尺寸相關 API 傳回的數字,包括 .outerHeight(),可能是小數。程式碼不應假設它是一個整數。此外,當使用者縮放頁面時,尺寸可能會不正確;瀏覽器不會公開 API 來偵測此狀況。
  • 當元素或其父元素被隱藏時,.outerHeight() 所回報的值無法保證準確。若要取得準確的值,請確保元素在使用 .outerHeight() 之前是可見的。jQuery 會嘗試暫時顯示然後再重新隱藏元素以測量其尺寸,但這並不可靠,而且(即使準確)也會對頁面效能造成重大影響。此顯示和重新隱藏測量功能可能會在未來的 jQuery 版本中移除。

範例

取得段落的 outerHeight。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>outerHeight demo</title>
<style>
p {
margin: 10px;
padding: 5px;
border: 2px solid #666;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<p>Hello</p><p></p>
<script>
var p = $( "p" ).first();
$( "p" ).last().text(
"outerHeight:" + p.outerHeight() +
" , outerHeight( true ):" + p.outerHeight( true ) );
</script>
</body>
</html>

示範

.outerHeight( value [, includeMargin ] )傳回: jQuery

說明: 設定已匹配元素集合中每個元素的 CSS 外部高度。

呼叫 .outerHeight(value) 時,value 可以是字串(數字和單位)或數字。如果只提供數字作為值,jQuery 會假設是像素單位。然而,如果提供字串,則可以使用任何有效的 CSS 測量值(例如 100px50%auto)。

範例

在第一次按一下時變更每個 div 的外高度(並變更其顏色)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>outerHeight demo</title>
<style>
div {
width: 50px;
padding: 10px;
height: 60px;
float: left;
margin: 5px;
background: red;
cursor: pointer;
}
.mod {
background: blue;
cursor: default;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<div>d</div>
<script>
var modHeight = 60;
$( "div" ).one( "click", function() {
$( this ).outerHeight( modHeight ).addClass( "mod" );
modHeight -= 8;
});
</script>
</body>
</html>

示範