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