目前正在开发一个视频播放器,如果视频是全屏的,则添加特定的样式类。如果用户使用esc而不是全屏按钮退出,样式将保持不变。/* View in fullscreen */function openFullscreen(elem) { if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } video.classList.add('video-fullscreen');}/* Close fullscreen */function closeFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { /* Safari */ document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { /* IE11 */ document.msExitFullscreen(); } video.classList.remove('video-fullscreen');}let fullscreen = false;//Toggle fullscreenfunction toggleFullScreen(){ !fullscreen ? openFullscreen(player) : closeFullscreen(); fullscreen = !fullscreen;}我尝试了esc按钮的事件监听器,这样我就可以用它来改变样式,第一个 esc 按下关闭,第二个按下我的代码,非常烦人://detect Escape key presswindow.addEventListener("keydown", (e) => { if(e.key === "Escape" && fullscreen){ e.preventDefault(); closeFullscreen(); fullscreen = !fullscreen; }});
2 回答
暮色呼如
TA贡献1853条经验 获得超9个赞
您不应该尝试拦截转义按键并从中得出对全屏模式的影响。相反,您应该监听fullscreenchange
事件- 如果失败也不会触发requestFullscreen
:
要了解其他 代码何时打开和关闭全屏模式,您应该
fullscreenchange
在Document
.fullscreenchange
例如,当用户手动切换全屏模式,或者当用户切换应用程序时,导致应用程序暂时退出全屏模式,倾听并注意也很重要。
document.addEventListener('fullscreenchange', (event) => { video.classList.toggle('video-fullscreen', document.fullscreenElement != null); });
但是,您可能根本不需要这个。只需在 CSS 中.video-fullscreen
使用:fullscreen
选择器即可,而不是使用类!
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
尝试将removeClass方法添加到您的事件侦听器回调函数中。
//detect Escape key press
window.addEventListener("keydown", (e) => {
if(e.key === "Escape" && fullscreen){
e.preventDefault();
video.classList.remove('video-fullscreen');
closeFullscreen();
fullscreen = !fullscreen;
}
});
添加回答
举报
0/150
提交
取消