gpt4 book ai didi

jquery - 如何启动/停止/重新启动 jQuery 动画

转载 作者:行者123 更新时间:2023-12-01 00:05:04 26 4
gpt4 key购买 nike

我有以下功能,当我调用时,会在一定时间内向用户显示一条消息(在我的例子中为 5 秒)。在此“期间”,如果我再次调用该函数以显示另一条消息,实际上它应该隐藏,然后重新显示新消息 5 秒钟。

下面的代码发生了什么,我调用该函数来显示消息。然后,假设在第 4 秒,我再次调用它以显示另一条消息,新消息显示 1 秒。

我需要以某种方式重置时间,但不知道如何重置。尝试停止动画,检查元素是否可见,如果可见则隐藏它,以及许多其他事情。我相信解决方案是一个简单的链接问题,但无法正确解决。因此,任何帮助将不胜感激!

function display_message(msgType, message) {

var elem = $('#ur_messagebox');

switch (msgType) {
case 'confirm':
elem.addClass('msg_confirm');
break;

case 'error':
elem.addClass('msg_error');
break;
}

elem.html(message);
elem.show().delay(5000).fadeOut(1000);
}

提前致谢...

最佳答案

简而言之,你不能使用 .delay()为了你想要的。它只是 setTimeout() 的包装。在下一个队列项目上,you can see the source here ,重要部分:

    return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});

所以这只是对 setTimeout() 进行排队,在执行时,使队列中的下一个项目出队并执行它。所以发生的事情是你添加了延迟,即使 .stop(true).clearQueue() ,当您对 .fadeOut() 进行排队时之后,您将其添加回相同 fx 队列,因此当 setTimeout() 在 5 秒内完成时,它会抓取 >新淡入淡出您排队并执行它。

您需要 setTimout() 并手动清除它,因为 jQuery 核心没有这个内置功能,如下所示:

function display_message(msgType, message) {
var mb = $('#ur_messagebox')
.addClass(msgType === 'confirm' ? 'msg_confirm' : 'msg_error')
.html(message)
.stop(true, true).fadeIn();
if(mb.data('delay')) clearTimeout(mb.data('delay'));
mb.data('delay', setTimeout(function() { mb.fadeOut(1000); }, 5000));
}

You can see a working demo here

关于jquery - 如何启动/停止/重新启动 jQuery 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2884221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com