How do I get the “auto” height of a DIV

2019-05-23 16:29发布

问题:

So when I set a fixed height on a div with jquery, like $('div').height(200);, the value of $('div').height() is always 200. Even if the content from that div exceeds that height (I use overflow:hidden).

How can I get that true height of the DIV as if it would be in "auto" mode ?

回答1:

USE

.scrollHeight()

element.scrollHeight

with jquery try this

 $(selector)[0].scrollHeight

DESCRIPTION

An element's scrollHeight is a measurement of the height of an element's content including content not visible on the screen due to overflow.

Example

DEMO from Vega's Answer



回答2:

You mean hidden content height?

Vega - yes. The height of the content of the div, including the part that gets hidden by overflow

Just set to auto and get the .height and set it back to the fixed height.

var $el = $('#test');
var tmp = $el.css('height');

var actualHeight = $el.css('height', 'auto').height();

$el.css('height', tmp);
alert(actualHeight);

DEMO: http://jsfiddle.net/sKZfF/