最近自己在写pc端的小项目(react + ts + mobx + react-intl ),写了一个全屏和退出全屏的功能,特此记录;

先上效果图:

代码部分

1.store部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 默认非全屏
@observable fullScreen: boolean = false;

// 全屏事件
@action
requestFullScreen = () => {
this.fullScreen = true;
var docElm = document.documentElement;
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
}
}

// 退出全屏
@action
exitFullscreen = () => {
this.fullScreen = false;
if (document.exitFullscreen) {
document.exitFullscreen();
}
}

2.dom部分

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* header 右侧功能区
*/
fullScreenRender = () => {
const { requestFullScreen, exitFullscreen } = this.store;
return (
{/* 此处为全屏按钮 */}
<span className="layout-header-trigger layout-header-trigger-min flex-align-center">
{fullScreen ? <span onClick={exitFullscreen} >{SVG.full2} </span> : <span onClick={requestFullScreen} >{SVG.full} </span>}
</span>
)
}

3.浏览器Esc自己关闭全屏处理

1
2
3
4
5
6
7
8
9
10
11
componentDidMount() {
// 全屏缩小
window.addEventListener('resize', () => {
let isFull:boolean = !!document.fullscreenElement;
if (!isFull) {
// 更改store中的值公共方法 changeObserver
this.store.changeObserver({ key: 'fullScreen', data: false });
}
})
}

4.兼容写法

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

//全屏
function fullScreen() {
var element = document.documentElement;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
}
}

//退出全屏
function exitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}

//监听window是否全屏,并进行相应的操作,支持esc键退出
window.onresize = function() {
var isFull=!!(document.webkitIsFullScreen || document.mozFullScreen ||
document.msFullscreenElement || document.fullscreenElement
);
// todo something
}


遇到问题

在写的过程中发现全屏了之后按Esc键是默认能退出全屏模式的,且在全屏模式下是监听不到键盘的onkeydown事件的,浏览器自己关闭了全屏模式,导致我在store中用来辨识是否全屏的fullScreen无法更改状态;后来发现浏览器切换全屏和非全屏会触发resize事件,全屏时document.fullscreenElement就是被全屏的dom内容,非全屏时document.fullscreenElement的值为空;由此有了上面第三步浏览器Esc自己关闭全屏处理,在按Esc键关闭全屏模式时,手动更改一下fullScreen的状态。