How to obtain clientWidth & clientHeight before DIV is visible

后端 未结 2 1311
迷失自我
迷失自我 2021-01-17 20:03

I want to obtain the dimensions of a DIV element (used to display a popup menu at the cursor position) while it\'s style.display=\'none;\', however the dimensio

2条回答
  •  無奈伤痛
    2021-01-17 20:38

    If your DIV is not visible, you won't be able to get its dimensions.

    However, there is a workaround. Your div has to be "visible", but that doesn't mean it's opacity and position have to be 1 and relative.

    Set the opacity to 0 and the position to "absolute" and you'll be able to get the DIV dimensions.


    EDIT

    Since I think more people will have a similar problem, I feel I should explain my answer a little more.

    If you try to get the size of a hidden element with JavaScript, you will always get 0.

    So there are techniques to get the real size without displaying the element to the user. My favourite is the one I already wrote about above. Here are the more detailed steps:

    1. you set the elements opacity to 0. This way it won't be displayed to the end user while you are getting the dimensions.

    2. you set the element position to "absolute". This way it won't take up any space.

    3. now it's safe to set the display to "inline-block".

    4. you read the elements dimensions. This time you'll get the real values.

    5. You set the display back to "hidden" and set the opacity and position back to its original values.

    And now you have the size of a hidden element.

提交回复
热议问题