jQuery animate height

2019-01-09 03:55发布

问题:

I have a button and a div with inside some text:

<h2>Click me</h2>
<div class="expand">Lot of text here....</div>

I want to show just 2 rows of the text as default, so I put height to 30px and overflow Hidden.

When I click on the H2 element I want animate the text to slideDown and if i click another time it will slideUp to the default height (30px).

I'm trying many things with jQuery, but it doesn't work.

EDIT:

I also have more than one "expand" and more than one "H2" and text is different into div, so the height is not fix... I would like to slide to the "auto" height or 100%.

Can someone help me? Thanks!

回答1:

You can store the height just before slimming it down to 30px on page load, for example:

$(".expand").each(function() {
  $.data(this, "realHeight", $(this).height());
}).css({ overflow: "hidden", height: "30px" });

Then in your click handler:

$("h2").toggle(function() {
  var div = $(this).next(".expand")
  div.animate({ height: div.data("realHeight") }, 600);
}, function() {
  $(this).next(".expand").animate({ height: 30 }, 600);
});

So what this does is get the .height() (run this in document.ready) before the overflow: hidden it set, and stores it via $.data(), then in the click handlers (via .toggle() to alternate), we use that value (or 30) every other click to .animate() to.



回答2:

The scrollHeight property of the DOM element could also give you the height you need.

$(".expand").animate({
    height : $(".expand")[0].scrollHeight
},2000);

Working example can be found at http://jsfiddle.net/af3xy/4/



回答3:

This thread is not the newest, but here's another approach.

I have been dealing with the very same issue today and could not get it to work properly. Even with the correct height calculated with height: auto applied, the animation would not give me the correct results. I tried putting it in $(window).load instead of $(document).ready, which helped a little, but still cut off my last line of text.

Instead of animating the height itself, I was able to resolve the issue by adding and removing a hidden class to my div dynamically. If you use jQuery-UI, you can apply a duration to these effects. This seems to work in all browsers, too.

Here's a working exampe.