Animate element to auto height with jQuery

2019-01-01 06:33发布

I want to animate a <div> from 200px to auto height. I can’t seem to make it work though. Does anyone know how?

Here’s the code:

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});

19条回答
看淡一切
2楼-- · 2019-01-01 06:58
  1. Save the current height:

    var curHeight = $('#first').height();
    
  2. Temporarily switch the height to auto:

    $('#first').css('height', 'auto');
    
  3. Get the auto height:

    var autoHeight = $('#first').height();
    
  4. Switch back to curHeight and animate to autoHeight:

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);
    

And together:

var el = $('#first'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000);
查看更多
皆成旧梦
3楼-- · 2019-01-01 06:59

Try this one ,

var height;
$(document).ready(function(){
    $('#first').css('height','auto');
    height = $('#first').height();
    $('#first').css('height','200px');
})

 $("div:first").click(function(){
  $("#first").animate({
    height: height
  }, 1000 );
});
查看更多
若你有天会懂
4楼-- · 2019-01-01 07:00

Your selectors don't seem to match. Does your element have an ID of 'first', or is it the first element in every div?

A safer solution would be to use 'this':

// assuming the div you want to animate has an ID of first
$('#first').click(function() {
  $(this).animate({ height : 'auto' }, 1000);
});
查看更多
唯独是你
5楼-- · 2019-01-01 07:03
var h = document.getElementById('First').scrollHeight;
$('#First').animate({ height : h+'px' },300);
查看更多
时光乱了年华
6楼-- · 2019-01-01 07:03

Use slideDown and slideUp

$("div:first").click(function(){ $("#first").slideDown(1000); });
查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 07:04

IMO this is the cleanest and easiest solution:

$("#first").animate({height: $("#first").get(0).scrollHeight}, 1000 );

Explanation: The DOM already knows from its initial rendering what size the expanded div will have when set to auto height. This property is stored in the DOM node as scrollHeight. We just have to fetch the DOM Element from the jQuery Element by calling get(0) and then we can access the property.

Adding a callback function to set the height to auto allows for greater responsiveness once the animation is complete (credit chris-williams):

$('#first').animate({
    height: $('#first').get(0).scrollHeight
}, 1000, function(){
    $(this).height('auto');
});
查看更多
登录 后发表回答