可能重复:
有没有一种方法可以检测浏览器窗口当前是否未激活?
我有一个每秒调用一次的函数,仅当当前页面位于前台时才运行,即用户没有最小化浏览器或切换到另一个选项卡。如果用户不看它,它可能没有用,并且可能占用大量CPU,因此我不想只在后台浪费时间。
有人知道如何用JavaScript讲这个吗?
注意:我使用jQuery,因此,如果您的答案使用了jQuery,那就很好了:)。
您将使用窗口的focus
和blur
事件:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
要回答“ Double Fire”的评论问题并保持在jQuery易用性之内:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句