浏览器中页面的visibility状态及变化监听

需求

在浏览器中播放视频,当用户进行页面切换操作时。需要根据视频播放页是否处于可见状态,来控制视频的暂停及重新播放。

相关文档

参考MDN中,关于页面的可见性相关的API说明。
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API

示例代码

html部分

<video width="800" height="100">
	<source src="myvideo.mp4" type="video/mp4"></source>
</video>

javascript部分

var pageVisibility = {
	hiddenProp: '',
	eventType: '',
	isVisible: function() {
		// 获取到的是不可见的状态值,所以这里需要否才是可见的状态值;
		return !document[this.hiddenProp];
	},
	init: function(handelEvent) {
		if(typeof document.hidden !== 'undefined') {
			this.hiddenProp = 'hidden';
			this.eventType = 'visibilitychange';
		} else if(typeof document.msHidden !== 'undefined') {
			this.hiddenProp = 'msHidden';
			this.eventType = 'msvisibilitychange';
		} else if(typeof document.webkitHidden !== 'undefined') {
			this.hiddenProp = 'webkitHidden';
			this.eventType = 'webkitvisibilitychange';
		}
		if(this.hiddenProp) {
			this.bindEvent(handelEvent);
		}
	},
	bindEvent: function() {
		document.addEventListener(this.eventType, this.handleEvent.bind(this), false);
	}
};
var handleVideoPlay = function(element) {
	if(pageVisibility.isVisible()) {
		element.play();
	} else {
		element.pause();
	}
};
var videoElem = document.querySelector('video');
pageVisibility.init(function() {
	handleVideoPlay(videoElem);
});

兼容性

兼容性的问题,直接在https://caniuse.com/#search=visibility查询,参考搜索结果中的 Page Visibility 部分。

原文地址:https://www.cnblogs.com/xiaoyucoding/p/7607470.html