我想要确定当用户在页面上时。
因此,当用户单击另一个窗口(失去焦点)或更改选项卡时,我应该停止在我的页面上播放视频。
问题是试图同时做这两件事。
例如,通过这个JS插件(JQuery Visbility),我能够检查我的页面的选项卡/窗口是否打开。
它是如何做到这一点的:
$(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.');
}
});但是它不能检测页面是否有焦点。例如,页面可能是打开的,但我可能会单独打开另一个窗口,并将焦点保持在那里。
下面的代码(摘自here)负责这一点:
function check()
{
if(document.hasFocus() == lastFocusStatus) return;
lastFocusStatus = !lastFocusStatus;
statusEl.innerText = lastFocusStatus ? 'with' : 'without';
}
window.statusEl = document.getElementById('status');
window.lastFocusStatus = document.hasFocus();
check();
setInterval(check, 200);现在,我正试图同时做这两件事。有可能吗?
发布于 2018-08-15 09:47:20
您可以为window的focus和blur事件添加事件侦听器。
var hasFocus = true;
$(window).focus(function(){
hasFocus = true;
});
$(window).blur(function(){
hasFocus = false;
});
//check the hasFocus variable to see if the window has focushttps://stackoverflow.com/questions/51851837
复制相似问题