Javascript / jQuery: get height when max-height is set to 0

Is it possible to get the css value of an attr height element if its max-height set to 0?

I need to know how many pixels an element displays onclick, and since each element has a different height, which varies with the size of the browser, I want to get the height values ​​from the css file.

http://jsfiddle.net/AqAJc/

+4
source share
4 answers

You can get the height of an element if you have max-height = 0 through the scrollHeight attribute. It works if you set a minimum weight but not height.

HTML:

 <div> Here you have a normal div <div id="toggable"> Something hidden is in here, but we can still get the height ! <div class="other-content"> Something else here </div> </div> </div> 

JS:

 alert(document.getElementById('toggable').scrollHeight) 

CSS: #toggable {max height: 0; overflow: hidden; }

 .other-content { min-height: 100px; } 

Demo: https://jsfiddle.net/asywL84u/2/

Link: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

+4
source

My first question is: why are you using max-height: 0; Is there anything else you can use? Like hide() show() that use display: none

The only thing I can do is remove the max-height css, get the height, and then reuse max-height:

 $('.div').css('max-height', 'none') console.log($('.div').height()) $('.div').css('max-height', '0') 

This should happen fast enough so you don't see the element, but it would be wise to hide it before removing max-height with

 $('.div').hide() $('.div').css('max-height', 'none') console.log($('.div').height()) $('.div').css('max-height', '0') $('.div').show() 
+2
source

Leave the maximum height from css. Load the height into a variable. Then add max-height to 0.

 $(function(){ var divHeight = $('.div').height(); $('.div').css('max-height', '0'); alert(divHeight); }); 

http://jsfiddle.net/AqAJc/4/

0
source
 $('.div').each(function(){ var t=$(this); // Cache jQuery reference t.css('max-height','none'); // Temporarily override max-height t.data('height',t.height()); // Store height in data t.css('max-height',''); // Remove our max-height override }); alert($('.div').data('height')); 

jsfiddle: http://jsfiddle.net/AqAJc/7/

0
source

Source: https://habr.com/ru/post/1495552/


All Articles