Need to find height of hidden div on page (set to display:none)

前端 未结 13 1618
萌比男神i
萌比男神i 2020-11-27 06:00

I need to measure the offsetHeight of a div that is inside of a hidden element.

13条回答
  •  生来不讨喜
    2020-11-27 06:50

    You need to make element's parent visible for that one very short moment while you're getting element's dimensions. In a generic solution, all ancestors are usually traversed and are made visible. Then their display values are set back to original ones.

    There are performance concerns of course.

    We considered this approach in Prototype.js implementation but ended up with getWidth and getHeight making only actual element visible, without traversing ancestors.

    The problem with alternative solutions - such as taking element out of "hidden" parent - is that certain styles might no longer apply to an element once it's out of its "regular" hierarchy. If you have a structure like this:

    
    

    and these rules:

    .bar { width: 10em; }
    .foo .bar { width: 15em; }
    

    then taking element out of its parent will actually result in wrong dimensions.

提交回复
热议问题