Home  >  Article  >  Web Front-end  >  Why Does jQuery\'s `height()` and `width()` Return Non-Zero Values for Elements with `display:none`?

Why Does jQuery\'s `height()` and `width()` Return Non-Zero Values for Elements with `display:none`?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 06:58:29439browse

Why Does jQuery's `height()` and `width()` Return Non-Zero Values for Elements with `display:none`?

jQuery's Unconventional Height() and Width() Behavior with "display:none"

jQuery's height() and width() methods are widely used to determine the visible dimensions of elements on a web page. However, there seems to be an unexpected behavior when dealing with elements that have the CSS property "display:none" set.

The Question

Traditionally, it was believed that elements with "display:none" have a height and width of zero. However, this is not always the case with jQuery. Consider the following example:

<code class="html"><div id="target" style="display:none;">
  a
</div></code>
<code class="css">alert($("#target").height());</code>

In this example, the height of the "target" element is not zero but rather a non-zero value. This inconsistency raises the question: why do elements with "display:none" sometimes return non-zero heights and widths in jQuery?

The Answer

To understand this behavior, we need to delve into the inner workings of jQuery's height() and width() methods. When an element has a visible offsetWidth of 0 (indicating it is "hidden"), jQuery attempts to calculate its actual dimensions. It does this by temporarily overriding the element's CSS properties:

  • position: "absolute"
  • visibility: "hidden"
  • display: "block"

With these modifications, jQuery retrieves the element's height, considering border and padding as necessary. Once the height is determined, jQuery restores the original CSS properties, ensuring no visible changes occur.

This process allows height() and width() to work correctly for hidden elements, as long as their parents are visible. Essentially, jQuery simulates the behavior of showing the element outside the document flow, retrieving its dimensions, and then hiding it again, all behind the scenes in a single operation. This eliminates the need for developers to manually show and hide elements to obtain their dimensions.

The above is the detailed content of Why Does jQuery\'s `height()` and `width()` Return Non-Zero Values for Elements with `display:none`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more