在前端开发中,经常会开发大屏显示,一般甲方都需要兼容PC和大屏的全屏模式,这里的全屏模式是html里面的body完全全屏哦,需要隐藏浏览器页签、状态栏、地址栏等,这个时候就需要用户可以自己选择是否全屏展示了,本解决方案可以兼容各大浏览器内核。先自己在网上找一个按钮的两个状态:全屏模式、非全屏模式,在本文文末也提供了按钮素材,可直接下载即可。

下面以Vue为例直接上可切换全屏关键的代码,react其实也可以使用只需要把js部分代码拷贝过去即可:

HTML部分:

1
2
3
4
5
6
7
8
<template>
<div class="header-box">
<div class="right-menu">
<a v-show="!isfull" href="javascript:void(0)" class="full-btn" @click="launchFullscreen" />
<a v-show="isfull" href="javascript:void(0)" class="full-btn fullscreen" @click="exitFullscreen" />
</div>
</div>
</template>

Javascript部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
export default {
name: 'AppHeader',
data() {
return {
isfull: false
}
},
mounted() {
// Events 兼容各大浏览器内核
document.addEventListener('fullscreenchange', function(e) {
console.log('fullscreenchange event! ', e)
})
document.addEventListener('mozfullscreenchange', function(e) {
console.log('mozfullscreenchange event! ', e)
})
document.addEventListener('webkitfullscreenchange', function(e) {
console.log('webkitfullscreenchange event! ', e)
})
document.addEventListener('msfullscreenchange', function(e) {
console.log('msfullscreenchange event! ', e)
})
},
methods: {
launchFullscreen() { // 进入全屏模式
const element = document.documentElement
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
} else if (typeof window.ActiveXObject !== 'undefined') { // for IE,这里其实就是模拟了按下键盘的F11,使浏览器全屏
// eslint-disable-next-line no-undef
const wscript = new ActiveXObject('WScript.Shell')
if (wscript != null) {
wscript.SendKeys('{F11}')
}
}
this.isfull = true
},
exitFullscreen() { // 退出全屏模式
if (document.exitFullscreen) {
document.exitFullscreen()
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen()
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen()
} else if (typeof window.ActiveXObject !== 'undefined') {
// for IE,这里和fullScreen相同,模拟按下F11键退出全屏
// eslint-disable-next-line no-undef
const wscript = new ActiveXObject('WScript.Shell')
if (wscript != null) {
wscript.SendKeys('{F11}')
}
}
this.isfull = false
}
}
}

CSS部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.header-box {
.right-menu {
display: flex;
height: 100%;
flex-direction: column;
margin-right: 20px;
justify-content: space-around;
a {
width: 18px;
height: 18px;
&.full-btn {
background: url('../../assets/common/full_bg.png') no-repeat 0 0;
&.fullscreen {
background: url('../../assets/common/full_bg.png') no-repeat -34px 0;
}
}
}
}
}

全屏按钮图片:引入公共scss文件