You would use the focus
and blur
events of the window:(您将使用窗口的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;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:(回答“双火”的评论问题并保持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);
})
Click to view Example Code Showing it working (JSFiddle)(单击以查看示例代码显示它正常工作(JSFiddle)) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…