jQuery 动画高度 [英] jQuery animate height
问题描述
我有一个按钮和一个 div,里面有一些文字:
I have a button and a div with inside some text:
<h2>Click me</h2>
<div class="expand">Lot of text here....</div>
我想默认只显示 2 行文本,所以我将高度设置为 30 像素并溢出隐藏.
I want to show just 2 rows of the text as default, so I put height to 30px and overflow Hidden.
当我点击 H2 元素时,我希望将文本设置为向下滑动,如果我再点击一次,它将向上滑动到默认高度(30 像素).
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).
我用 jQuery 尝试了很多东西,但它不起作用.
I'm trying many things with jQuery, but it doesn't work.
我也有不止一个展开"和不止一个H2",文本和 div 不同,所以高度不是固定的...我想滑动到自动"高度或 100%.
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!
推荐答案
您可以在页面加载时将其缩小到 30px 之前存储高度,例如:
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" });
然后在您的 click
处理程序中:
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);
});
所以它所做的是获得 .height()
(在 document.ready
) before overflow: hidden
它设置,并通过 $.data()
,然后在 click
处理程序中(通过 .toggle()
替代),我们使用该值(或 30)每隔一次点击 .animate()
to.
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.
这篇关于jQuery 动画高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!