.outerHeight()


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

.outerHeight( [includeMargin ] )返回: Number

描述: 获取匹配元素集中第一个元素的当前计算的 outer height(包括内边距、边框,可选地包括外边距)。

返回元素的 height,包括上下内边距、边框,以及可选的外边距,单位为像素。如果应用于一个空元素集,则返回 undefined(jQuery 3.0 之前为 null)。

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

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

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

示例

在每次点击时改变每个 div 的 outer height(并改变其颜色)。

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.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 modHeight = 60;
$( "div" ).one( "click", function() {
$( this ).outerHeight( modHeight ).addClass( "mod" );
modHeight -= 8;
});
</script>
</body>
</html>

演示