主要提供两个属性,一个事件(都在document对象上):
1. 属性:
1.1. hidden:获取或设置当前页面的可见性,boolean值;
1.2. visibilityState: 获取当前页面可见性状态,值为hidden、visibility其中一个
2. 事件:visibilityChange:页面可见性发生改变时触发的事件
3. 由于各类浏览器的支持情况不一致,都需要加上私有属性的前缀,如 webkit、moz、ms、o等。在ie9-不支持。
3. 可见性的应用场景:
3.1. 视频播放的切换
3.2. 用户状态的验证
const BROWER_PREFIX = ['webkit','moz','ms','o','']; class Utils{ constructor(){ this.isPageVisibilitySupport = false; this.prefix = ''; } /** * 获取驼峰命名格式的属性名 * @param prefix {string} 前缀 * @param value {string} 属性名 */ prefixToCamel( prefix, value){ if(prefix){ return prefix + value.slice(0,1).toUpperCase() + value.slice(1); } return value; } calculatePageVisibilitySupport(){ var that = this; BROWER_PREFIX.forEach(function (data) { if(!that.isPageVisibilitySupport && document[that.prefixToCamel(data,'hidden')] != undefined ){ that.isPageVisibilitySupport = true; that.prefix = data; } }); return that.isPageVisibilitySupport; } isHidden(){ if(this.calculatePageVisibilitySupport()){ return document[this.prefixToCamel(this.prefix,'hidden')]; } return undefined; } visibilityState(){ if(this.calculatePageVisibilitySupport()){ return document[this.prefixToCamel(this.prefix,"visibilitystate")]; } return undefined; } } export default Utils;
2.2. core类,提供外部可访问的静态方法和属性:import utils from 'src/utils'; var _utils = new utils(); class Core { static visibilityChange(callback){ if( _utils.calculatePageVisibilitySupport() && typeof callback == 'function'){ return document.addEventListener(Core.prefix + 'visibilitychange',function(event){ this.hidden = Core.hidden; this.visibilityState = Core.visibilityState; callback.call(this,event); }); return undefined; } } } Core.hidden = _utils.isHidden(); Core.visibilityState = _utils.visibilityState(); export default Core;
visibilityChange方法:实现page visibility值改变时触事件绑定。
三、源码GIT地址此包通过karma框架 + jasmine进行单元测试。源码通过babel
git@code.csdn.net:cqhaibin/visibilityproject.git