JS is relatively convenient to get the size of visible elements. You can use this method directly:
Fortunately, there is visibility:hidden in CSS, which is an invisible attribute. The biggest difference between it and display:none is that visibility:hidden has a physical size. If you have physical size, you can get the size through the above method, but after changing display:none to visibility:hidden, the page will have a blank space there. Even if you change visibility:hidden to display:none immediately after getting the size, the page will be there. Some parts will still shake a bit. Then the best way is to move the hidden element off the screen or out of the document flow (position: absolute). This seems perfect, but tragedy happens again. If you want to display this element again, the element will be invisible and the position is wrong, because this element visibility:hidden;position: absolute. So after getting the size, you have to restore the style back. Just set the position and visibility properties back to their original styles.
This is the basic implementation method of obtaining the size of hidden elements in js. If you are interested, you can read the method in the book "Mastering JavaScript".
I also made a simple demo here, you can take a look at the source code:
题外话:一般js的框架,库都已经封装了这个方法,比如jQ,我们可以直接使用 height()和width()方法获取隐藏元素的尺寸。