Javascript 检查页面的页面可见性和页面焦点
我想确定用户何时在页面上 因此,当用户单击另一个窗口(失去焦点)或更改选项卡时,我应该停止在页面上播放视频 问题是要同时做这两件事 例如,通过这个JS插件(),我可以检查页面的选项卡/窗口是否打开 下面是它是如何做到这一点的:Javascript 检查页面的页面可见性和页面焦点,javascript,jquery,visibility,Javascript,Jquery,Visibility,我想确定用户何时在页面上 因此,当用户单击另一个窗口(失去焦点)或更改选项卡时,我应该停止在页面上播放视频 问题是要同时做这两件事 例如,通过这个JS插件(),我可以检查页面的选项卡/窗口是否打开 下面是它是如何做到这一点的: $(document).on({ 'show': function() { console.log('The page gained visibility; the `show` event was triggered.');
$(document).on({
'show': function() {
console.log('The page gained visibility; the `show` event was triggered.');
},
'hide': function() {
console.log('The page lost visibility; the `hide` event was triggered.');
}
});
但它无法检测页面是否有焦点。例如,页面可能已打开,但我可能正在单独打开另一个窗口,并将焦点保持在那里
以下代码将处理该问题(取自):
现在,我正试图同时做这两件事。有可能吗?您可以为
窗口的焦点和模糊事件添加事件侦听器
var hasFocus = true;
$(window).focus(function(){
hasFocus = true;
});
$(window).blur(function(){
hasFocus = false;
});
//check the hasFocus variable to see if the window has focus
我建议使用页面可见性API。它归结为使用document.hidden
var hasFocus = true;
$(window).focus(function(){
hasFocus = true;
});
$(window).blur(function(){
hasFocus = false;
});
//check the hasFocus variable to see if the window has focus