返回值:Integerheight()
取得匹配集合中第一个元素经过计算后的高度。
-
1.0 新增height()
.css('height') 和 .height() 的区别在于,后者返回的是不带单位的像素值(例如,400)。然而,前者返回的是带单位的值(例如,400px)。建议在需要对元素的高度进行数学计算的场合使用 .height() 方法。
该方法同样可以取得 window 和 document 的高度。
$(window).height(); // returns height of browser viewport $(document).height(); // returns height of HTML document
注意,.height() 总是返回内容的高度,而不考虑 CSS 属性 box-sizing 的值。
注意: 尽管
style和script标签也有.width()和height()值,但是当绝对定义并给定display:block时,强烈不赞成在这些标签上调用上述方法。因为这种作法不但不好,而且其结果也被证明是不可靠的。
示例:
显示不同元素的高度。注意,由于例子中的高度值是来自 iframe 的,因此可能比实际值小。以黄色高亮形式显示的就是 iframe 的内主体。
<!DOCTYPE html>
<html>
<head>
<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="jquery.min.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(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "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>