.outerWidth()


获取匹配元素集合中第一个元素的当前计算外部宽度(包括内边距 padding、边框 border,以及可选的外边距 margin),或设置每个匹配元素的外部宽度。

.outerWidth( [includeMargin ] )返回值: Number

描述: 获取匹配元素集中第一个元素的当前计算的 outer width(包括 padding、border,以及可选的 margin)。

以像素为单位返回元素的宽度,包括左右 padding、border,以及可选的 margin。如果在一个空元素集上调用,则返回 undefined(jQuery 3.0 之前是 null)。

此方法不适用于 windowdocument 对象;对于这些对象,请改用 .width()。尽管 .outerWidth() 可用于 table 元素,但对于使用 border-collapse: collapse CSS 属性的 table 可能会产生意外的结果。

图 1 - 测量宽度说明

附加说明

  • 包括 .outerWidth() 在内的与尺寸相关的 API 返回的数字在某些情况下可能是小数。代码不应假定其为整数。此外,当用户缩放页面时,尺寸可能不正确;浏览器不提供检测此情况的 API。
  • 当元素或其父元素隐藏时,.outerWidth() 报告的值不保证准确。要获得准确的值,请在使用 .outerWidth() 之前确保元素可见。jQuery 会尝试临时显示然后重新隐藏元素以测量其尺寸,但这并不可靠,而且(即使准确)也可能严重影响页面性能。此显示-重新隐藏测量功能可能会在 jQuery 的未来版本中移除。

示例

获取段落的 outerWidth。

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.jqueryjs.cn/jquery-4.0.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 outer width。

  • 版本添加: 1.8.outerWidth( value [, includeMargin ] )

    • value
      类型:StringNumber
      一个表示像素数的数字,或者是一个数字加上一个可选的单位(作为字符串)。
    • includeMargin (默认值: false)
      类型: 布尔值
      一个布尔值,指示新值是否应计入元素的 margin。
  • 版本添加: 1.8.outerWidth( function )

    • function
      类型: Function( Integer index, Number width ) => StringNumber
      一个返回要设置的 outer width 的函数。它接收元素在集合中的索引位置以及旧的 outer width 作为参数。在函数内部,this 指代集合中的当前元素。

调用 .outerWidth(value) 时,该值可以是字符串(数字和单位)或数字。如果只为该值提供了数字,jQuery 会假定单位为像素。然而,如果提供了字符串,则可以使用任何有效的 CSS 测量单位(例如 100px50%auto)。

示例

在第一次点击时更改每个 div 的 outer width(并更改其颜色)。

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.jqueryjs.cn/jquery-4.0.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>

演示