在jQuery中选择DIV的真实高度

pat*_*ick 9 html jquery height

我有一个固定高度定义的DIV:

.w {
  height: 100px;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)

如果我在其中放置文本,它将隐藏超出100px的所有内容.我有一个显示所有文本的按钮,基本上它是这样的:

$('.w').height('auto');
Run Code Online (Sandbox Code Playgroud)

这将使所有文本可见,但我想动画这个.这不适用于height ='auto',它必须具有特定的高度.

问题是:如何获得DIV应该能够显示其中所有文本的高度?

The*_*iot 15

试试scrollHeight这样:

$('#ID_OF_DIV')[0].scrollHeight
Run Code Online (Sandbox Code Playgroud)

注意[0],因为它是DOM元素的属性.


T.J*_*der 8

您可以将高度设置为"自动",然后测量它,然后将其设置回来并启动效果.

像这样的东西(实例):

jQuery(function($) {

  // Div starts with "style='height: 10px; overflow: hidden"
  var div = $('#thediv');

  // On click, animate it to its full natural height
  div.click(function() {
    var oldHeight, newHeight;

    // Measure before and after
    oldHeight = div.height();
    newHeight = div.height('auto').height();

    // Put back the short height (you could grab this first
    div.height(oldHeight);
    div.animate({height: newHeight + "px"}, "slow");
  });  
});?
Run Code Online (Sandbox Code Playgroud)