相关文章推荐
曾经爱过的西装  ·  Modern Forms Designer ...·  1 月前    · 
沉稳的木瓜  ·  Delphi 10.3.3 - Indy ...·  1 年前    · 
鼻子大的脆皮肠  ·  SwiftUI 中 ...·  1 年前    · 
傻傻的针织衫  ·  javascript - ...·  1 年前    · 
<!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="https://code.jquery.com/jquery-latest.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>&nbsp;</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>

当调用 .height(value) 方法的时候,这个“value”参数可以是一个字符串(数字加单位)或者是一个数字。如果这个“value”参数只提供一个数字,jQuery会自动加上单位px。如果只提供一个字符串,任何有效的CSS尺寸都可以为高度赋值(就像 100px , 50% , 或者 auto )。注意在现代浏览器中,CSS高度属性不包含padding, border, 或者 margin。

如果没有给定明确的单位(像'em' 或者 '%'),那么默认情况下"px"会被直接添加上去(也理解为"px"是默认单位)。

注意 .height('value') 设置的容器宽度是根据CSS box-sizing 属性来定的, 将这个属性值改成 border-box ,将造成这个函数改变这个容器的outerHeight,而不是原来的内容高度。

点击每个div时设置该div高度为30px,并改变颜色。

<!DOCTYPE html>
<html>
<head>
<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-latest.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>