在前端开发中获取元素高度是最基础也是最常用的操作之一。本文将详细介绍原生JavaScript和jQuery中获取元素高度的各种方法帮你彻底搞懂它们的区别 目录原生JavaScript获取高度jQuery获取高度各方法对比实际应用场景常见问题解决一、原生JavaScript获取高度1️⃣offsetHeight⭐ 最常用获取元素的可见高度包括✅ 内容高度content✅ 内边距padding✅ 边框border❌ 不包括外边距marginconstdivdocument.getElementById(myDiv);constheightdiv.offsetHeight;console.log(height);// 例如: 200px数字类型不带px2️⃣clientHeight获取元素的内部高度包括✅ 内容高度content✅ 内边距padding❌ 不包括边框border❌ 不包括外边距marginconstdivdocument.getElementById(myDiv);constheightdiv.clientHeight;console.log(height);// 例如: 198px不含2px边框3️⃣getBoundingClientRect().height获取元素的精确高度浮点数包括✅ 内容 padding border✅ 返回精确到小数点的值constdivdocument.getElementById(myDiv);constheightdiv.getBoundingClientRect().height;console.log(height);// 例如: 198.5px精确值4️⃣scrollHeight获取元素的完整内容高度包括✅ 内容高度即使被隐藏/滚动✅ 内边距padding❌ 不包括边框和外边距constdivdocument.getElementById(myDiv);constheightdiv.scrollHeight;// 常用于判断内容是否溢出if(div.scrollHeightdiv.clientHeight){console.log(内容溢出了需要滚动);}二、jQuery获取高度jQuery提供了更简洁的API底层其实还是调用原生方法。1️⃣.height()⭐ 最常用varh$(#myDiv).height();console.log(h);// 200数字类型等价于原生的offsetHeight不含margin2️⃣.innerHeight()varh$(#myDiv).innerHeight();等价于原生的clientHeight含padding不含border3️⃣.outerHeight()varh$(#myDiv).outerHeight();// 含padding bordervarh$(#myDiv).outerHeight(true);// 含padding border margin4️⃣.css(height)varh$(#myDiv).css(height);console.log(h);// 200px字符串类型带px⚠️注意返回的是字符串需要解析才能计算三、各方法对比 方法内容PaddingBorderMargin返回类型JSoffsetHeight✅✅✅❌数字JSclientHeight✅✅❌❌数字JSgetBoundingClientRect().height✅✅✅❌浮点数JSscrollHeight✅✅❌❌数字jQuery.height()✅✅✅❌数字jQuery.innerHeight()✅✅❌❌数字jQuery.outerHeight()✅✅✅❌数字jQuery.outerHeight(true)✅✅✅✅数字jQuery.css(height)✅❌❌❌字符串四、实际应用场景 场景1判断内容是否溢出constdivdocument.getElementById(content);if(div.scrollHeightdiv.clientHeight){console.log(内容溢出需要滚动条);div.style.overflowYauto;}场景2居中对齐垂直居中functioncenterVertically(){constcontainer$(#container);constchild$(#child);constcontainerHcontainer.height();constchildHchild.outerHeight();child.css(margin-top,(containerH-childH)/2);}场景3响应式布局$(window).resize(function(){constwindowH$(window).height();constheaderH$(#header).outerHeight();$(#main).css(height,windowH-headerH-50);});场景4获取视口高度// 原生JSconstviewportHeightwindow.innerHeight;// jQueryconstviewportHeight$(window).height();五、常见问题解决 ❌ 问题1获取的高度为0原因元素还没渲染完成就获取了解决// 方案1放在DOM ready中$(document).ready(function(){varh$(#myDiv).height();});// 方案2图片加载完成后获取$(img).on(load,function(){varh$(this).height();});❌ 问题2.css(height)返回 “auto”原因元素高度由内容撑开没有显式设置解决// 使用 offsetHeight 代替varhdocument.getElementById(myDiv).offsetHeight;// 或 jQueryvarh$(#myDiv).height();❌ 问题3隐藏元素获取高度为0原因display: none的元素无法获取可视高度解决// 临时显示获取constdiv$(#myDiv);div.show();consthdiv.height();div.hide();// 或使用 scrollHeight即使隐藏也能获取consthdiv[0].scrollHeight; 总结该用哪个需求推荐方法获取元素总高度含边框.height()/offsetHeight⭐获取内容内边距高度.innerHeight()/clientHeight获取包含margin的总高度.outerHeight(true)判断内容是否溢出scrollHeight clientHeight获取精确浮点高度getBoundingClientRect().height获取CSS设置的高度值.css(height) 一句话总结日常开发用.height()最方便需要精确计算用原生offsetHeight判断溢出用scrollHeight觉得有用点赞收藏不迷路 ❤️有问题欢迎评论区交流