.height()
.height()
描述:获得匹配的元素集合中的第一个元素的当前经计算的高度。
该方法不接受任何参数
.css( "height" )和.height()的区别在后,后者返回一个无单位的像素值(比如说,400),而前者返回一个带完整单位的值(比如说,400px)。如果元素的高度需要用在数学计算中,推荐使用该.height()方法。

该方法也可以用来找到windows和document的高度。
// 返回浏览器视口的高度 $( window ).height(); // 返回HTML document的高度 $( document ).height();
注意.height()将总是返回内容的高度,无论CSS的box-sizing属性如何设置。自从jQuery 1.8,这可能需要检索CSS的高度加上box-sizing属性,然后如果元素具有box-sizing: border-box,还要减去每个元素上任何潜在的边框和内衬。要想避免这种处罚,请使用.css( "height" )而不是使用.height()。
注意:虽然<style>和<script>标签被设置了绝对定位并给定了display:block时,它们将对.width或.height()报告其值,但是强烈不建议在这些标签上调用那些方法。除了是一个糟糕的实践,结果也被证明是不可靠的。
其它说明
- 维度相关的API返回的数字,包括
.height(),在一些情况中可能是分数。代码不应该假定它是一个整数。当用户缩放网页的时候,维度可能不正确;浏览器没有提供侦测这种情况的API。 - 当元素或者它的父元素是隐藏元素的时候,
.height所报告的值不能保证精确。要想获得精确的值,在使用.height()之前请先检查元素的可见性。jQuery会试图临时地显示,然后再次隐藏元素,以测量它的维度,但是这是不可靠的,而且(甚至当精确测量时)会显著地影响了网页的性能。这种显示再重新隐藏的测主功能可能在jQuery的未来版本中被删除。
示例
显示各种各样的高度。注意值来自iframe,所以可能小于你的期待。黄色的高亮显示了iframe的主体。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>
body {
background: yellow;
}
button {
font-size: 12px;
margin: 2px;
}
p {
width: 150px;
border: 1px red solid;
}
div {
color: red;
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="getp">Get Paragraph Height</button>
<button id="getd">Get Document Height</button>
<button id="getw">Get Window Height</button>
<div> </div>
<p>
Sample paragraph to test height
</p>
<script>
function showHeight( element, height ) {
$( "div" ).text( "The height for the " + element + " is " + height + "px." );
}
$( "#getp" ).click(function() {
showHeight( "paragraph", $( "p" ).height() );
});
$( "#getd" ).click(function() {
showHeight( "document", $( document ).height() );
});
$( "#getw" ).click(function() {
showHeight( "window", $( window ).height() );
});
</script>
</body>
</html>
演示结果
.height()
描述:对每个匹配的元素设置CSS高度。
在调用.height(value)时,这个值可以是一个字符串(数字以及单位),或者是一个数字。如果只为该值提供了一个数字,jQuery假定单位是px。然而如果提供了一个字符串,必须为高度提供一个有效的CSS测量(比如说100px、50%或者auto)。注意,在现代浏览器中,CSS高度属性不包括padding、border或者margin。
如果没有显式指定单位(比如说“em”或“%”),则“px”将串联到值的后面。
注意,.height(value)设置了盒的内容高度,无论CSS属性box-sizing设置了什么值。
示例
点击任一个div,把这个div的高度设置成30像素,加一个颜色变化。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>
div {
width: 50px;
height: 70px;
float: left;
margin: 5px;
background: rgb(255,140,0);
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "div" ).one( "click", function() {
$( this ).height( 30 ).css({
cursor: "auto",
backgroundColor: "green"
});
});
</script>
</body>
</html>
演示结果