浏览器全屏功能js函数封装,带兼容性
本文封装一个网页全屏的切换功能 直接调用函数即可实现
1. utils工具代码:
// 全屏 export const fullScreen = { request () { const doc = document.documentElement if (doc.webkitRequestFullScreen) { doc.webkitRequestFullScreen() } else if (doc.mozRequestFullScreen) { doc.mozRequestFullScreen() } else if (doc.msRequestFullscreen) { doc.msRequestFullscreen() } else if (doc.requestFullScreen) { doc.requestFullScreen() } }, exit () { const doc = document.documentElement if (doc.mozRequestFullScreen) { document.mozCancelFullScreen() } else if (doc.webkitRequestFullScreen) { document.webkitCancelFullScreen() } else if (doc.msRequestFullscreen) { document.msExitFullscreen() } else if (doc.requestFullScreen) { document.exitFullScreen() } }, enable () { let status = document.fullscreen ?? document.isFullScreen ?? document.mozFullScreen ?? document.webkitIsFullScreen ?? document.webkitFullScreen ?? document.msFullScreen // IE if (status === undefined) { status = window.outerHeight === window.screen.height && window.outerWidth === window.screen.width } return status }, toggle () { let status = fullScreen.enable() if (status) { fullScreen.exit() } else { fullScreen.request() } }, listen (callback) { const doc = document.documentElement let eventName = 'fullscreenchange' if (doc.webkitRequestFullScreen) { eventName = 'webkitfullscreenchange' } else if (doc.mozRequestFullScreen) { eventName = 'mozfullscreenchange' } else if (doc.msRequestFullscreen) { eventName = 'msfullscreenchange' } document.addEventListener(eventName, callback) window.addEventListener('keydown', e => { e = e || window.event if (e.keyCode === 122) { e.preventDefault() fullScreen.toggle() } }) } }
2.使用方式:
<template> <div> <span @click="handleScreen">全屏切换</span> </div> </template> <script> import { fullScreen} from '你的js文件路径' export default { data () { return { isFullScreen: false } }, mounted () {
fullScreen.listen(() => {
this.isFullScreen = fullScreen.enable()
})
},
methods: {
handleScreen () {
fullScreen.toggle()
}
}
}
</script>
<style>
</style>
自律使我自由