我一直在使用这个,尽管直到最近我才意识到它在ie8中运行不正常。
$(window).blur(function () {
alert("lost");
});
在 Firefox 或 chrome 或 safari 中,这会导致在窗口失去焦点时显示警报。但是,在IE8中,警报似乎被放入某种队列中。警报"丢失"仅在窗口重新获得焦点时显示。更令人困惑的是,当与跟踪窗口是否获得焦点的事件相结合时,它们会失序。
$(window).focus(function () {
alert("gained");
});
(不要在Chrome或Firefox中尝试此操作,因为警报将进入某种周期)
如果这两个都与IE8一起使用,当窗口失去焦点,然后重新获得焦点时,IE8警报"获得"ok
"丢失"。这种无序事件触发会导致我的代码问题,因为它是向后的,并报告最后一个事件是浏览器失去焦点。
如何在IE8中跟踪此内容?
方法的功劳:https://stackoverflow.com/a/10999831/1026459
针对我的情况的解决方案:
document.onfocusout = function(){
alert("lost");
};
这实际上控制了一个间隔,但这不是重点。 onfocusout
适用于IE8,Chrome,Safari和FF。我不确定 ie8 对blur
有什么问题,但我正在逐步淘汰它。
编辑
不幸的是,document.onfocusout在chrome或safari中不起作用,所以我不得不做更多的解决方法。这是我最终得到的。
//ie workaround
document.onfocusout = function(e){
if( e === undefined ){//ie
var evt = event;//ie uses event
if( evt.toElement == null ){//check where focus was lost to
console.log("lost");
}
}
};
window.onblur = function(e){
if( e !== undefined ){//ie will have an undefined e here, so this screens them out
console.log("lost");
}
};
$(window).focus(function () {
console.log("gained");
});
在IE8中复制后,我测试了Mathias Bynnes 的页面可见性填充程序是否有效,它似乎解决了您的问题。您可以在此处下载:http://mths.be/visibility。
我确实稍微更改了您的测试代码以避免进入警报循环;
$(document).on({
'show.visibility': function () {
$(document.body).append(new Date().getTime() + '<br/>');
},
'hide.visibility': function () {
$(document.body).append(new Date().getTime() + '<br/>');
}
});
另请注意,这确实与 $(window).blur()
和 $(window).focus()
的行为略有不同,而不是在用户单击窗口元素外部时激活,在大多数浏览器(IE 除外)中,这只会在用户无法再看到窗口时激活(例如切换选项卡,或最小化浏览器,但在更改为不同的应用程序或监视器时不会激活)。我个人赞成这种行为,因为我不希望网站在我仍在观看但与其他应用程序交互时发生变化。