仅使用Javascript捕获ESC键

时间:2013-02-17 19:19:42

标签: javascript html html5 html5-video

我有一个自定义视频播放它自己的控件。我有一个脚本可以在用户输入并存在全屏时对控件进行更改。问题是当我使用ESC键而不是按钮退出全屏时,控件的样式更改不会被还原。我需要确保使用ESC或按钮退出全屏将导致相同的行为。

CSS:

function toggleFullScreen() {

  elem = document.getElementById("video_container");
  var db = document.getElementById("defaultBar"); 
  var ctrl = document.getElementById("controls");

  if (!document.fullscreenElement &&    // alternative standard method
      !document.mozFullScreenElement && !document.webkitFullscreenElement) {  // current working methods
    if (document.documentElement.requestFullscreen) {

          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          full.firstChild.src = ('images/icons/unfull.png');
          elem.requestFullscreen();          
        } else if (document.documentElement.mozRequestFullScreen) {
          full.firstChild.src = 'images/icons/unfull.png';
          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          elem.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {

          ctrl.style.width = '50%';
          ctrl.style.left = '25%';
          full.firstChild.src = 'images/icons/unfull.png';
          elem.webkitRequestFullscreen();

        }
  } else if (document.exitFullscreen) {
        full.firstChild.src = 'images/icons/full.png';
        ctrl.style.width = '100%';
        ctrl.style.left = '0';        
        document.exitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
        full.firstChild.src = 'images/icons/full.png';
        ctrl.style.width = '100%';
        ctrl.style.left = '0'; 
        document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen) {

        ctrl.style.width = '100%';
        ctrl.style.left = '0';
        full.firstChild.src = 'images/icons/full.png';
        document.webkitCancelFullScreen();
        } 
}

2 个答案:

答案 0 :(得分:6)

听起来您想要将按键事件附加到文档中。这样的事情应该可以解决问题。

document.onkeypress = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert("Esc was pressed");
    }
};

有关详细信息,请查看this article

答案 1 :(得分:1)

event.key ===" Escape"

更新,更清洁:使用event.key。没有更多的任意数字代码!

document.addEventListener('keydown', function(event) {
    const key = event.key; // Or const {key} = event; in ES6+
    if (key === "Escape") {
        // Do things
    }
});

Mozilla Docs

Supported Browsers