我可能有一个简单的问题需要解决,但我不知道什么是正确的方法。
我的网站顶部有一个默认隐藏的 div.notification
栏。如果需要,该栏会获得一个额外的 success
或 warning
类,将其设置为 display:block;
。
所以,有两种情况。要么在页面加载时将输出消息直接呈现到 .notification
栏(并且它会获得一类 success
或 warning
) 或 .notifcation
栏从顶部向下滑动并接收到 json 数据。
无论如何,通知栏应该始终可见 10 秒,然后再向上滑动。
因此我写了两个函数来处理这个栏。
var timing = 10000;
function notificationOutput(type, message) {
var note = $('.notification');
note.hide();
note.find('.message').html(message);
note.stop(true,true).slideDown().delay(timing).slideUp();
}
function notificationSlideUp(slideUp) {
var note = $('.notification');
if ( slideUp ) note.delay(timing).slideUp();
else note.stop(true,true).slideUp();
}
因此 notificationOutput()
函数由各种其他函数触发,这些函数返回 json 数据并将其呈现到框中。
notificationSlideUp()
函数现在在每次加载页面时都会被调用,因为在我的标题中我有这个......
<script type="text/javascript">
$(document).ready(function(){
notificationSlideUp(true);
});
</script>
这是有原因的!请记住 .notification
直接设置为在页面加载时可见的情况……例如当用户在我的平台上登录时,.notification
栏会立即显示并显示“欢迎用户名,您已成功登录”。
我在标题中调用了 notifictaionSlideUp()
函数,以确保当前可见的 .notification
栏会在 10 秒后再次 slideUp()。
这里出现了问题......
不知何故这导致整个通知时间和上下滑动“困惑”。所以必须有一些滑动功能和/或 delay() 功能的排队,因为 notificationOutput()
中没有 note.stop(true,true)
如果通知在页面加载后的前 10 秒内触发,则通知不会立即 slideDown() 函数。这是因为notificationSlideUp()
函数已经触发了对象的slideUp()和delay()。
同样的情况也发生在延迟上。如果 .notification
在前 10 秒内发出,则延迟时间不正确,因为延迟计数器已经在页面加载时启动。
知道如何解决这个问题以使其始终有效吗?
更新:
var notificationTimer;
function notificationOutput(type, message) {
var note = $('.notification');
note.hide();
note.find('.message').html(message);
note.stop(true,true).slideDown();
clearTimeout(notificationTimer);
notificationTimer = setTimeout(function() {
note.stop(true,true).slideUp();
}, 10000);
}
function notificationSlideUp(slideUp) {
var note = $('.notification');
if ( slideUp ) {
clearTimeout(notificationTimer);
notificationTimer = setTimeout(function() {
note.stop(true,true).slideUp();
}, 10000);
} else {
note.stop(true,true).slideUp();
}
}
最佳答案
不幸的是,jQuery 的 delay()
函数没有像 setTimeout()
对 clearTimeout()
那样提供任何取消延迟的方法>。我建议用命名的 setTimeout()
替换你的 delay()
,并为 clearTimeout()
写一个条件您需要立即取消/触发排队的动画。
关于javascript - jQuery:防止动画和超时排队?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9224455/