window.onfocus = function(){ // 窗口获取焦点事件};
window.οnblur= 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