我正在使用具有隐藏属性的 html5 文档对象来检测用户是否已切换到另一个选项卡。如何检查用户是否以相同的方式返回到当前选项卡?
请引用我的代码:
var PERIOD_NOT_VISIBLE = 60000;
var PERIOD_VISIBLE = 5000;
var timestring = 0;
(function callThis(timestring) {
//update notification
timer = setTimeout(function() {
callThis(timestring);
}, (document.hidden) ? PERIOD_NOT_VISIBLE : PERIOD_VISIBLE);
})();
每隔 5 秒更新一次通知。当前文档失去焦点时,间隔计时器增加到 1 分钟。所以这个最新的请求只会在 1 分钟后运行。
如果用户在 1 分钟完成之前的任何时间返回到文档,他仍然没有更新通知,因为他必须等待当前请求先完成。只有在那之后计时器才回到 5 秒。
是否可以在 1 分钟后不等待请求完成而检测用户是否返回当前文档?
最佳答案
您可以在窗口中使用blur
和focus
事件来检测它。
$(window).on("blur", function() {
// do whatever you want
$("body").append("<p>Windows lost focus</p>");
});
$(window).on("focus", function() {
// do whatever you want
$("body").append("<p>Windows got focus</p>");
});
这是一个工作示例 http://jsfiddle.net/uX84X/9/ (点击jsfiddle的结果框进行测试)
关于javascript - 如何检测文档是否回到焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40502392/