.outerWidth()


取得相符元素集合中第一個元素的目前計算外寬(包括內距、邊框,以及邊界),或設定每個相符元素的外寬。

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

說明:取得相符元素集合中第一個元素的目前計算外寬(包括內距、邊框,以及邊界)。

傳回元素的寬度,包括左右內邊距、邊框,以及可選擇的邊界,單位為像素。如果在一個空的元素集合上呼叫,會傳回 undefined(在 jQuery 3.0 之前為 null)。

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

圖 1 - 測量寬度的說明

其他注意事項

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

範例

取得段落的外部寬度。

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>outerWidth 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(
"outerWidth:" + p.outerWidth() +
" , outerWidth( true ):" + p.outerWidth( true ) );
</script>
</body>
</html>

示範

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

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

呼叫 .outerWidth(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>outerWidth demo</title>
<style>
div {
width: 60px;
padding: 10px;
height: 50px;
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 modWidth = 60;
$( "div" ).one( "click", function() {
$( this ).outerWidth( modWidth ).addClass( "mod" );
modWidth -= 8;
});
</script>
</body>
</html>

示範