jQuery height() 方法
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>
点击任意一个元素,其高度都会增加,如图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了