我的 js 代码的一部分出现了一些奇怪的行为。
我有一些通知出现在页面顶部的栏中,然后在一定时间后消失。我用一个简单setTimeout()
的方法来实现这一点。
有时,当页面加载时,一个特定的 url 查询字符串会显示一个通知,但是当用户单击一个按钮时,需要显示一个新的。我希望旧的消失,新的出现。我正在使用一个变量来保留对的引用setTimeout()
以取消它。但是,当我尝试这样做时,我设法创建了一个循环,最终导致我的 chrome 选项卡崩溃。
我整理了一个 jsfiddle 来说明我的问题 - http://jsfiddle.net/5Nm4c/
show notification
在另一个可见时单击将使浏览器选项卡崩溃。如果您在没有显示任何内容时单击它,那很好。
这是我的js:
var Notification = {
// close main notification bar
close: function (callback) {
$('#notification-bar').fadeOut(250, function () {
// reset its position and fade it back in so it is ready to go again
$(this).css('top', -100).fadeIn(1);
// check if a callback function has been passed in
if (typeof callback === 'function') {
callback();
}
});
},
// open notification bar with the appropriate css class and message
open: function (message) {
// if the notification bar is already visisble
if (verge.inViewport($('#notification-bar'))) {
// hide and then show it with the new message
window.clearTimeout(Notification.timeout);
Notification.close(Notification.open(message));
return false;
}
$('#notification-bar').html(message);
$('#notification-bar').animate({
'top': 0
}, 250, function () {
Notification.timeout = window.setTimeout(function () { Notification.close() }, 1500);
});
},
timeout: null
}
Notification.open('hello');
$('#button').click(function(e){
e.preventDefault();
Notification.open('link clicked');
});
我正在使用https://github.com/ryanve/verge/因为它有一些很好的方法来检查元素是否在视口中可见。
有人可以告诉我我的错误在哪里吗?