本文概述
jQuery height()方法用于返回第一个元素的当前计算高度, 或设置每个匹配元素的高度。换句话说, 可以说height()方法用于两个目的:
返回高度:使用此方法返回高度时, 它将返回第一个匹配元素的高度。
设置高度:使用此方法设置高度时, 它将设置所有匹配元素的高度。
此方法是一个非常常见的jQuery维度。
before()和insertBefore()这两个方法均用于执行相同的任务。它们之间的主要区别在于语法以及内容和目标的位置。
句法:
要返回高度:
$(selector).height()
设置高度:
$(selector).height(value)
通过使用功能设置高度:
$(selector).height(function(index, currentheight))
jQuery height()方法的参数
参数 | 描述 |
---|---|
Value | 这是必填参数。它以px, em, pt等指定高度。默认单位为px。 |
Function (index, currentHeight) | 这是一个可选参数。这用于指定一个函数, 该函数返回所选元素的新高度。索引:提供元素在集合中的索引位置。 currentHeight:提供所选元素的当前高度。 |
jQuery height()方法的示例
让我们以一个示例来演示jQuery height()方法。
返回高度:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Height of div: " + $("div").height());
});
});
</script>
</head>
<body>
<div style="height:100px;width:200px;padding:10px;margin:3px;border:1px solid blue;background-color:lightpink;"><div class="div">Hello Guys!<br/> This is srcmini02.com</div></div><br>
<button>Display the height of div</button>
</body>
</html>
立即测试
jQuery height()示例2
设置高度:
本示例将说明如何设置特定的高度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>height demo</title>
<style>
div {
width: 50px;
height: 100px;
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( 50 ).css({
cursor: "auto", backgroundColor: "green"
});
});
</script>
</body>
</html>
立即测试
评论前必须登录!
注册