首页  >  文章  >  web前端  >  没有显式设置 CSS 高度时如何获取 Div 的高度?

没有显式设置 CSS 高度时如何获取 Div 的高度?

Patricia Arquette
Patricia Arquette原创
2024-10-27 06:26:03816浏览

How to Get the Height of a Div When No Explicit CSS Height is Set?

在没有显式 CSS 规则的情况下确定 Div 高度

如果 CSS 中没有显式设置高度,则获取 div 的高度可能会很困难。虽然 .height() jQuery 方法通常用于此目的,但它需要现有的 CSS 规则才能实现正确的功能。这是另一种方法:

jQuery 高度函数

jQuery 提供了一系列高度函数,即使没有 CSS 高度规则,也可以提供准确的高度测量:

  • .height(): 不包括内边距、边框和边距。
  • .innerHeight(): 包括内边距,但不包括边框和边距。
  • .outerHeight(): 包括边框,但不包括边距。
  • .outerHeight(true): 包括边距。

使用演示

以下代码片段演示了如何使用这些函数:

<code class="js">$(function() {
  var $heightTest = $('#heightTest');
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')
});</code>

输出:

div 的计算高度显示在 div 本身中,提供有关每个函数输出的详细信息。

以上是没有显式设置 CSS 高度时如何获取 Div 的高度?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn