最近自己在写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
|
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) { 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.onresize = function() { var isFull=!!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement ); }
|
遇到问题
在写的过程中发现全屏了之后按Esc
键是默认能退出全屏模式的,且在全屏模式下是监听不到键盘的onkeydown
事件的,浏览器自己关闭了全屏模式,导致我在store
中用来辨识是否全屏的fullScreen
无法更改状态;后来发现浏览器切换全屏和非全屏会触发resize
事件,全屏时document.fullscreenElement
就是被全屏的dom内容,非全屏时document.fullscreenElement
的值为空;由此有了上面第三步浏览器Esc自己关闭全屏处理
,在按Esc
键关闭全屏模式时,手动更改一下fullScreen
的状态。