window.onfocus = function(){ // 窗口获取焦点事件};

window.onblur= function(){ // 窗口失去焦点事件};
有弊端,亲测。

所以我还有一个更好的办法,就是监听页面是否在当前,而不是最小化或离开了。

document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
// 我回来了。
}
}); 2018年12月7日:补充,有兼容问题。
于是我找到了这个兼容代码:
// 兼容代码到ie9
(function() {
let hidden = 'hidden';
const onchange = function(evt) {
const v = 'visible';
const h = 'hidden';
const evtMap = { focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h };
evt = evt || window.event;
if (evt.type in evtMap) {
document.body.className = evtMap[evt.type];
} else {
document.body.className = this[hidden] ? 'hidden' : 'visible';
}
};
// Standards:
if (hidden in document) {
document.addEventListener('visibilitychange', onchange);
} else if ((hidden = 'mozHidden') in document) {
document.addEventListener('mozvisibilitychange', onchange);
} else if ((hidden = 'webkitHidden') in document) {
document.addEventListener('webkitvisibilitychange', onchange);
} else if ((hidden = 'msHidden') in document) {
document.addEventListener('msvisibilitychange', onchange);
} else if ('onfocusin' in document) {
// IE 9 and lower:
document.onfocusin = document.onfocusout = onchange;
} else {
// All others:
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
}
// set the initial state (but only if browser supports the Page Visibility API)
if (document[hidden] !== undefined) {
onchange({type: document[hidden] ? 'blur' : 'focus'});
}
})();

  

大神的地址:https://www.cnblogs.com/zichi/p/5158745.html

最新文章

  1. Gcc的编译流程分为了四个步骤:
  2. 微信JS SDK Demo
  3. Java和MongoDB之Hello World
  4. 有趣的js符号{}、[]、""、~、++等转换
  5. 面试题30.最小的k个数
  6. JavaScript 基础一
  7. Android studio 查看sha1
  8. HAProxy安装文档
  9. 微信公众号开发,weUi组件,问题总结
  10. 关于<Servlet>定义
  11. jmeter实例介绍
  12. 华为4K机顶盒EC6108V9U从原联通更换为电信的IPTV账号成功经验
  13. 部分视图 - partial
  14. 几种实现one-hot编码的方式
  15. ie6定位absolute bug触发layout解决
  16. MUI class="mui-switch" 开关监听
  17. mysql报错Establishing SSL connection without server's identity verification is not recommended
  18. Extjs如何添加多个Vtype
  19. 自己写一个java的mvc框架吧(四)
  20. poj1001 Exponentiation【java大数】

热门文章

  1. USACO Section 2.1 Sorting a Three-Valued Sequence 解题报告
  2. 解题:ZJOI 2006 皇帝的烦恼
  3. 【POJ1958】汉诺塔+
  4. openstack遇到的错误
  5. 最小化安装k8s
  6. C# 编码规范、命名规则
  7. windows服务写完之后怎么让它跑起来
  8. Eclipse的一些常用的快捷键
  9. DNA序列编码中Hairpin的定义和计算
  10. np.random.rand均匀分布随机数和np.random.randn正态分布随机数函数使用方法