jquery 动画意外延迟
Unexpected delays in jquery animations
我有一个最初设置为 max-height: 200px; overflow-y:hidden;
的列表元素。在该元素下方有一个 h3
元素,您可以单击它来显示整个列表。为此,我使用 jQuery animate() 方法为元素的 maxHeight
-属性 设置了动画。动画应持续 1.2 秒。之后,列表下方的文本从 "show more" 变为 "show less"。当您单击它时,此动画会反转,持续时间为 1.2 秒,之后文本变回 "show more"。
一切正常,除了一些意外的延迟:在引发列表的 maxHeight
-属性 的第一个动画之后,文本也需要一秒钟左右的时间才能更改。然后,如果您单击 "show less" 文本,在动画开始前的大约一秒钟内什么也没有发生。
是什么导致了这些意外的延迟?
编辑: 正如 Wa Kei 所解释的,这个延迟是由 "excess" 高度引起的,因为元素实际上不到 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
我有一个最初设置为 max-height: 200px; overflow-y:hidden;
的列表元素。在该元素下方有一个 h3
元素,您可以单击它来显示整个列表。为此,我使用 jQuery animate() 方法为元素的 maxHeight
-属性 设置了动画。动画应持续 1.2 秒。之后,列表下方的文本从 "show more" 变为 "show less"。当您单击它时,此动画会反转,持续时间为 1.2 秒,之后文本变回 "show more"。
一切正常,除了一些意外的延迟:在引发列表的 maxHeight
-属性 的第一个动画之后,文本也需要一秒钟左右的时间才能更改。然后,如果您单击 "show less" 文本,在动画开始前的大约一秒钟内什么也没有发生。
是什么导致了这些意外的延迟?
编辑: 正如 Wa Kei 所解释的,这个延迟是由 "excess" 高度引起的,因为元素实际上不到 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