如何仅在按住键时播放视频?

问题描述 投票:0回答:2

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

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

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

javascript html
2个回答
0
投票

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>

-1
投票

您可以使用keyupkeydown事件将您的视频playpause

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


document.onkeydown = function(e) {
  vid.play();
}

document.onkeyup = function(e) {
  vid.pause();
}
<video width="320" height="240" controls id="myVideo">
  <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>
© www.soinside.com 2019 - 2024. All rights reserved.