Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

animation - jQuery animate height

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...