首頁  >  文章  >  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