【发布时间】:2011-07-18 09:47:51
【问题描述】:
我试图在按下按钮时将 div 设置为完整高度,如果再次单击按钮则返回到其原始高度。 div 的全高是自动的,因为它包含具有不同字数的文本。我尝试执行以下代码,但无法正常工作。
CSS:
.category_brief{
text-align:justify;
height:100px;
overflow:hidden;
}
示例 1:此代码在打开到 full height 时不对 div 进行动画处理,但在返回到旧高度时进行动画处理。
$(".slide").toggle(function(){
$('.category_brief').animate({height:'100%'},200);
},function(){
$('.category_brief').animate({height:100},200);
});
示例 2:此代码的输出与示例 1 相同
var toggle = true, oldHeight = 0;
$('.slide').click(function(event) {
event.preventDefault();
var $ele = $('.category_brief');
var toHeight = ((toggle = !toggle) ? oldHeight : newHeight);
oldHeight = $ele.height();
var newHeight = $ele.height('auto').height();
$ele.animate({ height: toHeight });
});
示例 3:此代码将 div 设置为完整高度但不切换。
var slide = $('.slide');
var slidepanel = $('.category_brief');
// On click, animate it to its full natural height
slide.click(function(event) {
event.preventDefault();
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"});
});
如果可能的话,请提供一点解释,因为我是新手..
更新:由@chazm 的想法解决..
@chazm:谢谢你的想法。我通过结合第一个和第三个示例来实现它...这是代码以防万一有人需要它。
var slidepanel = $('.category_brief');
$(".slide").toggle(function(){
var oldHeight, newHeight;
// Measure before and after
oldHeight = slidepanel.height();
newHeight = slidepanel.height('auto').height();
// Put back the short height (you could grab this first
slidepanel.height(oldHeight);
slidepanel.animate({height: newHeight + "px"})
},function(){
$('.category_brief').animate({height:100},300);
});
【问题讨论】:
-
@Wesley Murch:它现在被删除了......
标签: javascript animation height jquery-animate