.keypress无法在浏览器中工作(Chrome除外)

时间:2017-01-29 11:12:32

标签: javascript html video html5-video keydown

我有一个js,除了chrome之外没有在任何浏览器中工作?可能是.keydown函数会造成麻烦。有一段代码。它是作为交互式视频制作的,当按下键时,应弹出不同的视频层。

    var videos = document.querySelectorAll("video");
var promises = Promise.all(Array.prototype.slice.call(videos).map(function(video) {
    return new Promise(function(resolve, reject) {
      video.addEventListener("canplaythrough", resolve);
      video.addEventListener("error", reject);
    })
  }))
  .then(function() {
    videos.forEach(function(video) {
      video.play();
    });
    videos[2].style.display = "none";
    document.addEventListener("keydown", function(e) {
      var key = e.key;
      if (key === "b" || key === "B") {
        videos[2].style.display = "block";
        videos[1].style.display = "none";
        videos[0].style.display = "none";
      }
    });
    videos[1].style.display = "none";
    document.addEventListener("keydown", function(e) {
      var key = e.key;
      if (key === "a" || key === "A") {
        videos[2].style.display = "none";
        videos[1].style.display = "block";
        videos[0].style.display = "none";
      }
    });
    document.addEventListener("keyup", function(e) {
      videos[2].style.display = "none";
      videos[1].style.display = "none";
      videos[0].style.display = "block";
    });
    window.focus();
  })
  .catch(function(err) {
    console.log(err);
  });

浏览器不会出现任何错误。而且我不知道从哪里开始。有什么想法吗?

HTML:

<html>
  <head>
    <body bgcolor="#00">
    <center><img src="head.png" alt="Head"></center>
  </head>
 <style>
 video {
  position: absolute;
  left: 12vw;
}
.full-frame {
    width:75%%;
    height:75%
}
</style>
<br><br>
<div id="video"; overflow: hidden">
   <video src="1.mov" style="width: 75%; height: 75%;" autoplay loop></video>
    <video src="2.mov" style="width: 75%; height: 75%;" autoplay loop></video>
   <video src="3.mov" style="width: 75%; height: 75%;" autoplay loop></video>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

尝试使用

  

document.body.addEventListener()

而不是document.addEventListener()

答案 1 :(得分:0)

据我所知,键盘相关事件仅在元素具有焦点时触发。所以基本上你需要把重点放在正确的工作上。如何在窗口对象上附加事件?

window.addEventListener('keydown', (e) => console.log(e.keyCode))

我刚检查了chrome和FF,两者都有效。