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

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

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
    }
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744760123a4592123.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信