0

如果视频是全屏的,目前正在开发一个添加了特定样式类的视频播放器如果用户使用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 fullscreen
function toggleFullScreen(){
    !fullscreen ? openFullscreen(player) : closeFullscreen();
    fullscreen = !fullscreen;
}

我为esc按钮尝试了一个事件侦听器,因此我可以使用它来更改样式,第一次 esc 按下关闭,第二次执行我的代码,非常烦人:

//detect Escape key press
window.addEventListener("keydown", (e) => {
    if(e.key === "Escape" && fullscreen){
        e.preventDefault();
        closeFullscreen();
        fullscreen = !fullscreen;
   }
});

4

2 回答 2

0

您不应该尝试拦截转义键并从中得出对全屏模式的影响。相反,您应该监听fullscreenchange事件requestFullscreen- 如果失败也不会触发:

要了解其他代码何时打开和关闭全屏模式,您fullscreenchange应该Document. 同样重要的fullscreenchange是要注意何时,例如,用户手动切换全屏模式,或用户切换应用程序,导致您的应用程序暂时退出全屏模式。

document.addEventListener('fullscreenchange', (event) => {
  video.classList.toggle('video-fullscreen', document.fullscreenElement != null);
});

但是,您可能根本不需要这个。不用.video-fullscreen类,只需在 CSS 中使用:fullscreen选择器!

于 2020-11-05T20:15:17.623 回答
0

尝试将 removeClass 方法添加到您的事件侦听器回调函数中。

//detect Escape key press
window.addEventListener("keydown", (e) => {
    if(e.key === "Escape" && fullscreen){
        e.preventDefault();
        video.classList.remove('video-fullscreen');        
        closeFullscreen();
        fullscreen = !fullscreen;
   }
});
于 2020-11-05T18:26:11.880 回答