如何用空格键播放/暂停HTML 5视频?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (674)

如何使用e.key暂停HTML 5视频和空格键?逻辑有点不对劲.。

    <div class=modal-video id="v-5417">
    <div class=video-player>
                    <video id=v-5417-tape preload="none">
                        <source type="video/mp4" src="videos/anthem-od47.mp4">
                        <source type="video/webm" src="videos/anthem-od47.webm">
                    </video>
                    <div class="close-modal fade-control"></div>
                </div>
            </div>

JS

$( document ).on( 'keydown', function ( e ) {
            if ( e.keyCode === 32 ) {
                if (video.paused == true) {
                    // Play the video
                    video.play();
                }else{
                    if(video.play == true){
                    video.pause();
                    }
                }
            }
        });
提问于
用户回答回答于

var videoPlayer = document.getElementById('Video1')
$(window).keypress(function(e) {
  if (e.keyCode == 0 || e.keyCode == 32) {
	if (videoPlayer.paused == false) {
            videoPlayer.pause();
            videoPlayer.firstChild.nodeValue = 'Play';
        } else {
            videoPlayer.play();
            videoPlayer.firstChild.nodeValue = 'Pause';
        }
  
  }
});
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
  <script src="/website/js/playPause.js></script>
</head>
<body>
  <center>
    <h1>Video</h1>
    <video id="Video1" autoplay="yes">
      <source src="videoName.mp4" type="video/mp4" />
    </video>
  </center>
</body>
</html>

用户回答回答于

这个应该管用:

// Press spacebar to Play/Pause.
    var body = $( 'body' );

    body.keypress( function ( e ) {
        if ( e.which == 32 ) {
            // Stop the jerk.
            e.preventDefault();

            // If video is paused.
            if ( theVideo.get(0).paused == true ) {
                theVideo.get(0).play();
            } else {
                theVideo.get(0).pause();
            }
        }
    }); // End keypress().

扫码关注云+社区

领取腾讯云代金券