Why does jQuery\'s `.height()` and `.width()` methods return values for elements with `display: none`?

Barbara Streisand
Release: 2024-10-29 03:37:30
Original
617 people have browsed it

Why does jQuery's `.height()` and `.width()` methods return values for elements with `display: none`?

jQuery: .height()/.width() and "display:none"

Despite the popular assumption that elements with "display:none" return zero for jQuery's .height() and .width() methods, this is not always the case. In the provided example, the target element returns a non-zero height even though it is hidden.

Why does this occur?

According to jQuery's source code, if an element's offsetWidth is 0 (indicating that jQuery considers it "hidden"), a series of steps are taken to determine the height:

  1. The element's position is set to "absolute".
  2. Visibility is set to "hidden".
  3. Display is set to "block".

This effectively moves the element out of the document flow, calculates the height while accounting for border/padding, and then reverts the previous settings.

So, jQuery essentially makes the element visible temporarily, calculates the height, and makes it invisible again, all before the UI actually updates. This allows .height() and .width() to work even on hidden elements as long as their parents are visible.

The .height() and .width() methods handle this showing/hiding process internally, so developers do not need to manually implement such checks in their code.

The above is the detailed content of Why does jQuery\'s `.height()` and `.width()` methods return values for elements with `display: none`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template