jQuery height() 方法

发布时间 2023-04-04 17:11:34作者: yinghualeihenmei

https://blog.csdn.net/m0_57835615/article/details/117827323

jQuery height( ) 方法可用于设置或返回被选元素的高度。返回元素的高度时, 只返回匹配到的第一个元素的高度。设置元素的高度时,所有匹配到的元素的高度都会被设置。

值得一提的是,该方法不包含元素的内外边距以及边框。

(1)返回元素的高度

语法格式:

$(selector).height()
示例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$(".box").click(function(){
alert("高度为" + $(this).height() + "px");
})
})
</script>
<style>
.box {
width: 100px;
height: 100px;
padding: 10px;
margin: 5px;
border: 3px solid #ccc;
background-color: rgba(14, 207, 62, 0.589);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>

点击元素时,将弹出对话框:

 

可见,返回的高度不包含元素的内外边距以及边框。

(2)设置元素的高度

语法格式:

$(selector).height(value)
示例:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$(".box").click(function(){
$(this).height(200 + "px");
})
})
</script>
<style>
.box {
width: 100px;
height: 100px;
background-color: rgba(56, 14, 207, 0.589);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>

点击元素时,元素的高度将边为200px:

  

(3)使用函数增加元素的高度

语法格式:

$(selector).height(function(index,currentValue))
参数:

index:元素的索引号

currentValue:元素的当前高度值

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../jQuery/jQuery.js"></script>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).height(function(index,currentValue){
return currentValue + 10 + "px";
})
})
})
</script>
<style>
.box1 {
float: left;
width: 100px;
height: 100px;
background-color: rgba(56, 14, 207, 0.589);
}
.box2 {
float: left;
width: 100px;
height: 100px;
background-color: rgba(14, 207, 72, 0.589);
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>

  

点击任意一个元素,其高度都会增加,如图: