Home  >  Article  >  Web Front-end  >  How to get the height and width of hidden elements (display:none) in javascript_javascript skills

How to get the height and width of hidden elements (display:none) in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:45:323001browse

JS is relatively convenient to get the size of visible elements. You can use this method directly:

Copy code The code is as follows:

function getDefaultStyle(obj,attribute){ // Return the final style function, compatible with IE and DOM, set parameters: element object, style characteristics
return obj.currentStyle?obj.currentStyle[attribute ]:document.defaultView.getComputedStyle(obj,false)[attribute];
}


But if this element is hidden (display:none), the size is unknown. Adaptable, how can the above method not work! Because elements with display:none have no physical size! Tragedy happened like this!

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:

Copy the code The code is as follows:





js获取隐藏元素的尺寸



 


 
       
点我

       

题外话:一般js的框架,库都已经封装了这个方法,比如jQ,我们可以直接使用 height()和width()方法获取隐藏元素的尺寸。

Statement:
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