我有以下功能,当我打电话时,会在一定时间内(在我的情况下为 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/