How do you find the dimensions of a “display: none” element?

后端 未结 6 829
轻奢々
轻奢々 2021-02-13 18:58

I have some child elements inside a div that gets the CSS display: none applied to it and I want to find out what the child element dimensions are. How can I do thi

6条回答
  •  梦如初夏
    2021-02-13 19:37

    For someone who need this to implement a context menu or hint window:

    The getComputedStyle() isn't seem to work on elements that have dynamic width/height. All you get is auto.

    My approach was to set visibility: hidden and setting display other than none (what would required to show your element).

    I used this 3 step method in a context menu component for calculating where to place the menu relative to the click position to always be on-screen:

    1. set visibility: hidden and remove display: none (set to what it will be when the menu finally shown)
    2. get the dimensions
    3. remove visibility: hidden

    It will probably still not work when the parent also has display: none but that wasn't an issue for this use case as one can not (should not) access a context menu of an object that is not shown anyway.

提交回复
热议问题