如何仅在按住HTML键的情况下播放视频

时间:2019-10-26 01:18:19

标签: javascript html

我有用于按某个键的代码,但是我需要实现按住键的位置才能播放视频

var vid = document.getElementById('myVideo');   
document.onkeypress = function(e){
    if((e || window.event).keyCode === 112){
        vid.paused ? vid.play() : vid.pause();

我知道我必须使用onkeydown和onkeyup,但不确定如何使用

1 个答案:

答案 0 :(得分:2)

const vid = document.getElementById('myVideo');

const playPauseVideo = ev => {
  if (ev.key !== 'F1') return; // Do nothing if not F1
  ev.preventDefault();         // Prevent browser default action (on F1)
  vid[ev.type === 'keydown' ? 'play' : 'pause']();
}

document.addEventListener('keydown', playPauseVideo);
document.addEventListener('keyup', playPauseVideo);
Press and hold F1 to play video
<video id="myVideo" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"></video>