您可能在想为什么不使用html的视频循环来循环播放视频。问题是当我循环播放视频时,它不是平滑无缝的。我试图寻找其他解决方案,但没有找到。所以我试图反而让视频在结束时(或接近结束时)跳回到开头。
如何使用javascript执行此操作?
<video autoplay id="testvideo" width="100%" height="900px">
<source src="examplevideo.mp4" type="video/mp4" />
</video>
答案 0 :(得分:1)
这将在视频到达结束时循环播放:
var video = document.getElementById('testvideo')
// When the 'ended' event fires
video.addEventListener('ended', function(){
// Reset the video to 0
video.currentTime = 0;
// And play again
video.play();
});
&#13;
<video id="testvideo" autoplay controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
&#13;
如果你想早点做,你可以查看timeupdate - 在这种情况下,我会检查我们是否达到了75%的视频。
var video = document.getElementById('testvideo')
// When the 'ended' event fires
video.addEventListener('timeupdate', function(){
if(video.currentTime > video.duration * .75){
// Reset the video to 0
video.currentTime = 0;
// And play again
video.play();
}
});
&#13;
<video id="testvideo" autoplay controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
&#13;
请记住,搜索(重置时间)将始终稍微加速,因为必须搜索数据。解决这个问题的唯一方法是潜在地使用两个视频,然后在另一个视频结束之前从一个视频转换到另一个视频。以下代码有点广泛但实际上非常简单。
// Get both videos
var video1 = document.getElementById('testvideo');
var video2 = document.getElementById('testvideo2');
// Add an event that will switch the active class when the video is about to end
// CSS3 transitions will take into effect and fade one into the other.
video1.addEventListener('timeupdate', function(){
if(video1.currentTime > video1.duration - .5){
video1.className = '';
video2.className = 'active';
video2.play();
}
});
video2.addEventListener('timeupdate', function(){
if(video2.currentTime > video2.duration - .5){
video2.className = '';
video1.className = 'active';
video1.play();
}
});
// This will reset the video to be replayed
video1.addEventListener('ended', function(){
video1.currentTime = 0;
});
video2.addEventListener('ended', function(){
video2.currentTime = 0;
});
&#13;
video {
position: absolute;
top: 0;
left: 0;
-webkit-transition: opacity 500ms;
transition: opacity 500ms;
}
video.active {
z-index: 1;
opacity: 1;
-webkit-transition-delay: 200ms;
transition-delay: 200ms;
}
&#13;
<video id="testvideo" class="active" autoplay controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
<video id="testvideo2" controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
&#13;