我有一个列表元素,最初设置为 max-height: 200px; overflow-y:hidden;
。在该元素下方有一个 h3
- 您可以单击元素来显示整个列表。为此,我对 maxHeight
进行了动画处理。 - 使用 jQuery animate() 方法的元素属性。动画应持续 1.2 秒。之后,列表下方的文字从“显示更多”变为“显示更少”。当您单击它时,该动画会反转,同样持续 1.2 秒,之后文本变回“显示更多”。
一切工作正常,除了一些意外的延迟:在第一个动画引发 maxHeight
之后- 列表的属性,文本也需要另一秒钟左右的时间才能更改。然后,如果您单击“显示较少”文本,则在动画开始之前大约一秒钟内不会发生任何事情。
是什么导致了这些意外的延误?
编辑: 正如 Wa Kei 所解释的,这种延迟是由“超额”高度引起的,因为该元素的高度实际上小于 1200px。那么我怎样才能重新设计我的函数,使其按预期工作,而不必使用固定的高度值呢? 我无法使用方便的 jQuery 方法,如toggle()、show() 或hide(),因为所有这些方法都完全隐藏对象,而不是接受最小和最大高度或类似的东西。 我愿意接受 JS/JQuery/CSS 的不同解决方案,但 html 结构应保持不变。
最佳答案
这是第一部分的示例:
if (!list.hasClass('opened')) {
list.animate({
maxHeight: '1200px'
}, {
duration: 1200,
progress: function(){
if(list.css('maxHeight') > list.css('height')) {
$(this).stop();
}
},
always: function() {
$('#show_more').text('(weniger anzeigen)');
list.addClass('opened');
}
});
}
编辑: 我稍微修改了你的代码:http://jsfiddle.net/z83cpbvj/1/
@progress (jQuery API) A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties.
@always (jQuery API) A function to be called when the animation completes or stops without completing
关于javascript - jquery 动画出现意外延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30710254/