监听全屏切换事件
document.addEventListener('fullscreenchange', (event) => {
// document.fullscreenElement will point to the element that
// is in fullscreen mode if there is one. If there isn't one,
// the value of the property is null.
console.log(event)
// document.fullscreenElement 有值说明是全屏状态 null 是非全屏
if (document.fullscreenElement) {
console.log(`Element: ${document.fullscreenElement.id} entered full-screen mode.`);
} else {
console.log('Leaving full-screen mode.');
}
});
注意:
- 通过 F11 进入全屏后
document.fullscreenElement的值还是null, 不会触发fullscreenchange事件。 - 只有通过事件进入全屏退出全屏才会触发
fullscreenchange事件 - 先判断
document.fullscreenEnabled是否支持全屏,不支持应该给提示
进入全屏事件
fullScreen = () => {
// document.requestFullscreen 已弃用, 使用 Element.requestFullscreen() 方法发出异步请求,以使元素以全屏模式显示。
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullScreen) {
document.documentElement.webkitRequestFullScreen();
}
}
退出全屏事件
// document.fullscreenElement 只读属性返回当前在此文档中以全屏模式显示的 Element,如果当前未使用全屏模式,则返回null。
exitFullScreen = () => {
if (document.fullscreenElement) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozFullScreenElement) {
document.mozCancelFullScreen();
} else if (document.webkitFullscreenElement) {
document.webkitCancelFullScreen();
}
}