JavaScript实现全屏和退出全屏功能
Author:zhoulujun Date:
我们有时候需要手动去设置浏览器全屏事件,这里写了一个函数,
//兼容谷歌 火狐 IE
全屏操作代码
class EventListen { constructor () { this.handers = [] } /** *事件监听 * @param event {string} 事件名称 * @param fn {function} 触发函数 */ on (event, fn) { if (!this.handers[event]) { this.handers[event] = [] } this.handers[event].push(fn) } /** *触发函数 * @param event {string} 事件名 * @param rest {*} 事件名 */ triger (event, ...rest) { let fns = this.handers[event] // 没有订阅 则返回 if (!fns || fns.length === 0) { return null } fns.forEach(function (fn) { fn.apply(this, rest) }) return null } } /** * 操作浏览器全屏状态函数,默认操作整个页面,函数判断六七千 * @param element {Object} 需要操作全屏状态的元素,默认document.documentElement * @param isFullScreen 不传,自动判断当前元素是否为全屏状态 * @param callback 回调函数 * @return {Boolean} */ const fullscreenchange = Symbol('fullscreenchange') const fullscreenerror = Symbol('fullscreenerror') class FullScreen extends EventListen { constructor (available = false, enabled = true) { super(null) this.available = available this.enabled = enabled document.addEventListener('fullscreenchange', this[fullscreenchange].bind(this)) document.addEventListener('webkitfullscreenchange', this[fullscreenchange].bind(this)) document.addEventListener('mozfullscreenchange', this[fullscreenchange].bind(this)) document.addEventListener('MSFullscreenChange', this[fullscreenchange].bind(this)) // 监听浏览器器退出全屏 document.addEventListener('fullscreenerror', this[fullscreenerror].bind(this)) document.addEventListener('webkitfullscreenerror', this[fullscreenerror].bind(this)) document.addEventListener('mozfullscreenerror', this[fullscreenerror].bind(this)) document.addEventListener('MSFullscreenError', this[fullscreenerror].bind(this)) } [fullscreenchange] (e) { this.triger('fullscreenchange', e) } [fullscreenerror] (e) { this.triger('fullscreenerror', e) } adjustFullScreenStatus (element = document.documentElement, isFullScreen, callback) { if (isFullScreen === undefined) { isFullScreen = document.isFullScreen || document.webkitIsFullScreen || document.mozIsFullScreen } const requestFullScreenFun = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullscreen if (!isFullScreen) { if (typeof requestFullScreenFun === 'function' && requestFullScreenFun) { requestFullScreenFun && requestFullScreenFun.call(element) callback && callback() return true } } else { (document.exitFullscreen && document.exitFullscreen()) || (document.webkitCancelFullScreen && document.webkitCancelFullScreen()) || (document.mozCancelFullScreen && document.mozCancelFullScreen()) || (document.msExitFullscreen && document.msExitFullscreen()) callback && callback() } return false } } let f = new FullScreen() f.adjustFullScreenStatus() f.on('fullscreenchange', (e) => { console.log('fullscreenchange') console.log(e) }) f.on('fullscreenerror', (e) => { console.log('fullscreenerror') })
包括
转载本站文章《JavaScript实现全屏和退出全屏功能》,
请注明出处:https://www.zhoulujun.cn/html/webfront/SGML/html5/2016_0616_8229.html