简体   繁体   中英

jQuery — how to animate a div using height:auto

I have a div that expands downward when a user presses "more." The div's height is always auto, and expands to fit the content accordingly.

I need to keep "height:auto" so that the CSS remains responsive when the screen is resized, but I want the changing height to be animated...how should I do that?

In other words, when the user presses more and additional content is added to this div, I want the div's expansion to be animated, without specifying a certain height like 5em or anything.

<div id="expand">
    <p>This is the div I want to expand</p>
    <div id="hidden" style="display:none">
       <img />
       <img />
    </div>
</div>

Got it! I need to use the slideToggle method on the instead of the Thanks!

jsBin demo <-- Resize the window. Works great.

You can do it simply like:

$('.more').click(function(){
  $("+ div", this).slideToggle();
});

having:

<button class="more">MORE</button>
<div>Lorem Ipsum...</div>

I would use the HTML you have, but that's the price when you did not showed some code in your Question ;)

I don't know exactly how you set up your code, but jQuery

$(link).on("click", function() {
   $(element).slideToggle();
});

might work for you.

Is that what you are looking for?

You can always:

var targetDiv = $('.targetDiv');
// get original Height
var originalHeight = targetDiv.height();
// get natural height
targetDiv.css({ height: 'auto'});
var naturalHeight = targetDiv.height();
// reset div to original height
targetDiv.css({height: originalHeight});
// animate to target height
targetDiv.animate({
   height: naturalHeight}, {
   duration: 1000,
   completion: function() {
      // set height to auto
      targetDiv.css({height: 'auto'});
   });

You can do this using jQuery. You just need to caluclate the height: auto absolute height.

JSFiddle: http://jsfiddle.net/CS2h9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM