开发者

selecting the true height of a DIV in jQuery

I have a DIV defined with a fixed height:

.w {
  height: 100px;
  overflow: hidden;
}

if I put text in this it wil开发者_开发技巧l hide everything that goes beyond the 100px. I have a button that shows all text, basically it does this:

$('.w').height('auto');

this will make all text visible, but I would like to animate this. And that won't work with height='auto', it has to have a specific height.

The question: how do I get the height the DIV should be to be able to show all text in it?


try scrollHeight like this:

$('#ID_OF_DIV')[0].scrollHeight

Note [0], as it is property of DOM elements.


You could set the height to 'auto', then measure it, then set it back and start the effect.

Something like this (live example):

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");
  });  
});​


T.J. Crowder's answer didn't work for me because "oldHeight" was a calculated pixel value, different than the rem value I had specified in my stylesheet. Also, the inline style overrode a different height I had for another media query. So, instead of saving the "oldHeight" and putting it back later, I just cleared jQuery's inline style by setting css 'height' to an empty string.

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() {
        // Measure after
        var newHeight = div.height('auto').height();

        // Remove inline styles
        div.css('height', '');
        div.animate({height: newHeight + "px"}, "slow");

    });  
});​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜