方法来源:张鑫旭博客。
今天有个需求,浏览器页面切换时执行一下事件,但是F5刷新页面时,不需要执行。网上找到了解决办法。
考虑到浏览器兼容性,封装的公用对象,这个对象有俩个属性,一个方法,如下:
var pageVisibility = (function() { var prefixSupport, keyWithPrefix = function(prefix, key) { if (prefix !== "") { // 首字母大写 return prefix + key.slice(0,1).toUpperCase() + key.slice(1); } return key; }; var isPageVisibilitySupport = (function() { var support = false; if (typeof window.screenX === "number") { ["webkit", "moz", "ms", "o", ""].forEach(function(prefix) { if (support == false && document[keyWithPrefix(prefix, "hidden")] != undefined) { prefixSupport = prefix; support = true; } }); } return support; })(); var isHidden = function() { if (isPageVisibilitySupport) { return document[keyWithPrefix(prefixSupport, "hidden")]; } return undefined; }; var visibilityState = function() { if (isPageVisibilitySupport) { return document[keyWithPrefix(prefixSupport, "visibilityState")]; } return undefined; }; return { hidden: isHidden(), // 当前tab窗口离开时为true,进入时为false visibilityState: visibilityState(), // 当前tab窗口离开时为hidden,进入时为visible visibilitychange: function(fn, usecapture) { // 当前tab窗口离开或者进入时会执行该事件 usecapture = undefined || false; if (isPageVisibilitySupport && typeof fn === "function") { return document.addEventListener(prefixSupport + "visibilitychange", function(evt) { this.hidden = isHidden(); this.visibilityState = visibilityState(); fn.call(this, evt); }.bind(this), usecapture); } return undefined; } }; })(undefined);
需要时调用对象的 visibilitychange 方法:
pageVisibility.visibilitychange(function(){ if(!pageVisibility.hidden){ // 页面进入时才执行 console.log("你切换回当前页面啦..."); } })