最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to listen on keydown event in video tag? - Stack Overflow

programmeradmin0浏览0评论

I have a <video> tag and want to listen on its keydown event. Below is the code:

html:

<div>
<video src=".mp4" controls onkeydown="key()">
  </video>
</div>

javascript:

function key(e) {
  console.log(e.keyCode)
}

when I play the video and type some key from keyboard, it doesn't fire the key function. what is the correct way to listen on a video key event?

I also tried below code but it doesn't work:

document.querySelector("video").onkeydown = function(e) {
  console.log(e.keyCode)
  }

I have a <video> tag and want to listen on its keydown event. Below is the code:

html:

<div>
<video src="https://www.w3schools./html/mov_bbb.mp4" controls onkeydown="key()">
  </video>
</div>

javascript:

function key(e) {
  console.log(e.keyCode)
}

when I play the video and type some key from keyboard, it doesn't fire the key function. what is the correct way to listen on a video key event?

I also tried below code but it doesn't work:

document.querySelector("video").onkeydown = function(e) {
  console.log(e.keyCode)
  }
Share Improve this question edited Oct 21, 2018 at 3:03 Joey Yi Zhao asked Oct 21, 2018 at 2:28 Joey Yi ZhaoJoey Yi Zhao 42.8k88 gold badges358 silver badges662 bronze badges 1
  • Are you sure need a keydown event? I mean, Video element offers some methods and events for you to track down and do something on video. html5rocks./en/tutorials/video/basics – HalfWebDev Commented Oct 21, 2018 at 3:08
Add a ment  | 

3 Answers 3

Reset to default 7

To get a button press event called, you need to be focused on the element specified. Here, for some reason, you can't focus on the video automatically, so just hack it in when you play the video like this:

var video = document.getElementById('vid')

video.addEventListener('keydown', (e) => {
  console.log(e);
});

video.addEventListener('play', () => {
  video.focus();
});

jsfiddle: https://jsfiddle/238bygu7/

(Also make sure to add an id to your video in this case)

var video = document.getElementsByTagName('video')[0]
video.addEventListener('keypress', function (e) {
  console.log(e)
})
video.addEventListener('playing', function (e) {
  video.focus()
})
<video src="https://www.w3schools./html/mov_bbb.mp4" controls></video>

The key event is captured only when the DOM element is focus.

document.getElementsByTagName('video')[0].addEventListener('keydown', function(e){
    if(e.key === 'Enter'){
        //Your Code Here
    }
});
发布评论

评论列表(0)

  1. 暂无评论