要检测页面是否处于全屏模式,可以使用 JavaScript 提供的 Fullscreen API。以下是一个简单的示例代码,演示如何检测页面是否处于全屏模式:
// 检测页面是否处于全屏模式
function isPageFullscreen() {
return !!(document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement);
}
// 监听全屏状态变化
document.addEventListener('fullscreenchange', function () {
if (isPageFullscreen()) {
console.log('页面已进入全屏模式');
} else {
console.log('页面已退出全屏模式');
}
});
// 进入全屏
function requestFullscreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
// 退出全屏
function exitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
// 示例:点击按钮进入/退出全屏
const fullscreenButton = document.getElementById('fullscreen-button');
fullscreenButton.addEventListener('click', function () {
if (isPageFullscreen()) {
exitFullscreen();
} else {
requestFullscreen(document.documentElement);
}
});
在上面的示例中,`isPageFullscreen` 函数用来检测页面是否处于全屏模式,`requestFullscreen` 函数用来请求进入全屏,`exitFullscreen` 函数用来退出全屏。另外,通过监听 `fullscreenchange` 事件可以实时获取页面的全屏状态变化。
标签:requestFullscreen,document,js,else,全屏,element,监听,页面 From: https://blog.csdn.net/2301_81449444/article/details/141095602