如何让视频暂停,播放另一个视频,然后恢复原始视频

时间:2017-03-29 15:54:33

标签: javascript html5 video event-handling

我有两个视频,我希望第一个视频播放10秒,暂停,播放第二个视频,当第二个视频停止播放时,返回播放第一个视频,然后停止播放。有点像广告/商业广告。目前我有两个视频,在第一个完全结束后按顺序播放。我知道解决方案是在javascript事件处理程序中,但我似乎无法做到正确。任何帮助将不胜感激。

HTML:

<div class="vidBox" id="contain">

  <video id="video1" class="vid" muted controls="true" height="300" width="500">
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

</div>

JavaScript的:

var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo() {
    var vid = document.getElementById('video1');
    var vid2 = document.getElementById('video2');
    vid.removeEventListener("ended", hideVideo, false);
    vid.style.display='none';
    vid2.style.display='block';
}

1 个答案:

答案 0 :(得分:1)

这是一个解决方案,在chrome,safari,firefox上测试:(我更改了第二个视频,以便能够判断它是否正常工作,但您可以设置您想要的那个):

<!DOCTYPE html> 
<html> 

<head>
</head>
<body> 

<div class="vidBox" id="contain">

  <video id="video1" class="vid" muted controls="true" height="300" width="500" autoplay>
      <source src="http://jcath-drg.s3.amazonaws.com/BigBuck.m4v" type="video/mp4">
  </video>

  <video id="video2" class="vid2" autoplay muted controls="true" style="display:none;" height="300" width="500">
    <source src="myVideo3.mp4" type="video/mp4">
  </video>

</div>

<script type="text/javascript">
var vid = document.getElementById('video1');
vid.addEventListener("ended", hideVideo, false);

function hideVideo(event) {
    console.log("hideVideo");
    var vid = document.getElementById('video1');
    vid.pause();
    vid.style.display='none';
    vid.removeEventListener("ended", hideVideo, false);

    var vid2 = document.getElementById('video2');
    vid2.style.display='block';
    vid2.addEventListener("ended", hideVideo2, false);
    vid2.load();
}

function hideVideo2(event) {
    console.log("hideVideo2");
    var vid2 = document.getElementById('video2');
    vid2.style.display='none';

    var vid = document.getElementById('video1');
    vid.style.display='block';
    vid.play();
}

// start timer in milliseconds
setTimeout( hideVideo, 10000);

</script>

</body> 
</html>