在HTML5视频中添加事件监听器以播放,暂停和跳至秒

时间:2016-11-01 03:38:30

标签: javascript html5 video addeventlistener

我有一个HTML5视频,用于展示产品的运作方式。单击某个数字的每个图像时,我希望它跳到视频中的某个时间,然后在某个时间停止。

以下是我目前正在使用的代码:



<img id="stepOne" src="http://9e9.921.myftpupload.com/wp-content/uploads/2016/10/Step-1.png" /><img id="stepTwo" src="http://9e9.921.myftpupload.com/wp-content/uploads/2016/10/Step-2.png" /><img id="stepThree" src="http://9e9.921.myftpupload.com/wp-content/uploads/2016/10/Step-3.png" />

<video id="myvideo" width="300" height="150">
<source src="/videos/howitworks.mp4" type="video/mp4" />
<source src="/videos/howitworks.webm" type="video/webm=" />
Your browser does not support HTML5 video.</video>
&#13;
&#13;
&#13;

使用Javascript

&#13;
&#13;
var myvideo = document.getElementById('myvideo')
var stepone = document.getElementById('stepOne')
var steptwo = document.getElementById('stepTwo')
var stepthree = document.getElementById('stepThree')

stepone.addEventListener("click", function (event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 0;
    myvideo.play();
}, false);


steptwo.addEventListener("click", function(event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 10;
    myvideo.play();
}, false);


stepthree.addEventListener("click", function(event) {
    event.preventDefault();
    myvideo.play();
    myvideo.pause();
    myvideo.currentTime = 32;
    myvideo.play();
}, false);
&#13;
&#13;
&#13;

可以直播here

我没有添加任何内容以使其在达到某个时间时停止,因为此当前脚本根本不执行。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

当我转到您的页面时,我看到错误Uncaught TypeError: Cannot read property 'addEventListener' of null,所以这可能是您的问题:)

脚本可能在元素准备好之前运行。尝试将该代码包装在document.addEventListener("DOMContentLoaded", function(event) {中,看看是否可以解决问题?

所以

document.addEventListener("DOMContentLoaded", function(event) { 
  var myvideo = document.getElementById('myvideo')
  var stepone = document.getElementById('stepOne')
  var steptwo = document.getElementById('stepTwo')
  var stepthree = document.getElementById('stepThree')

  stepone.addEventListener("click", function (event) {
      event.preventDefault();
      myvideo.play();
      myvideo.pause();
      myvideo.currentTime = 0;
      myvideo.play();
  }, false);


  steptwo.addEventListener("click", function(event) {
      event.preventDefault();
      myvideo.play();
      myvideo.pause();
      myvideo.currentTime = 10;
      myvideo.play();
  }, false);


  stepthree.addEventListener("click", function(event) {
      event.preventDefault();
      myvideo.play();
      myvideo.pause();
      myvideo.currentTime = 32;
      myvideo.play();
  }, false);
});