
height()方法获取或设置所选元素的高度。
当height()方法用于获取高度时,它将返回第一个选定元素的高度。
当height()方法用于设置高度时,它将设置所有选定元素的高度。
如下图所示,height()方法不包含padding,border或margin:

高度值也可以是相对的。如果为值提供了前导+=或-=字符序列,则通过从当前值中加上或减去给定的数值来计算目标高度(例如 height("+ = 50"))。
语法:
获得高度:
$(selector).height()
设置高度:
$(selector).height(value)
使用函数设置高度:
$(selector).height(function(index, currentHeight))
实例
获取DIV元素的高度:
$("div").click(function(){
$(this).height();
});测试看看‹/›设置所有段落的高度:
$("button").click(function(){
$("p").height(50);
});测试看看‹/›使用不同的单位设置所有段落的高度:
$("#btn1").click(function(){
$("p").height(50);
});
$("#btn2").click(function(){
$("p").height("7em");
});
$("#btn3").click(function(){
$("p").height("100vh");
});测试看看‹/›单击按钮时,增加所有段落的高度(使用功能):
$("button").click(function(){
$("p").height(function(i, val){
return val * 2;
});
});测试看看‹/›height()方法还能够找到窗口和文档的高度:
$(window).height();// 返回浏览器窗口的高度 $(document).height(); // 返回HTML文档的高度测试看看‹/›
显示width(),height(),innerHeight(),innerWidth(),outerWidth()和outerHeight()之间的差异:
$("button").click(function(){
$("div").width();
$("div").innerWidth();
$("div").outerWidth();
$("div").height();
$("div").innerHeight();
$("div").outerHeight();
});测试看看‹/›用户滚动页面时添加平滑滚动效果:
let size = $(".main").height(); // 获取".main" 高度
$(window).keydown(function(event) {
if(event.which === 40) { // 如果按向下箭头键
$("html, body").animate({scrollTop: "+=" + size}, 300);
} else if(event.which === 38) { // 如果按向上箭头键
$("html, body").animate({scrollTop: "-=" + size}, 300);
}
});测试看看‹/›参数值
| 参数 | 描述 |
|---|---|
| value | 表示像素数的整数,或附加了可选度量单位的整数(作为字符串) |
| function(index, currentHeight) | 指定一个函数,该函数返回所选元素的高度
|