您可能在想,为什么不直接使用html的视频循环来循环视频。问题是,当我循环视频,它不是平滑和无缝的。我曾试图寻找其他解决方案,但没有找到任何解决办法。所以我试着让视频在结束(或接近结束)时跳回起点。
如何使用javascript完成此操作?
<video autoplay id="testvideo" width="100%" height="900px">
<source src="examplevideo.mp4" type="video/mp4" />
</video>发布于 2015-09-18 14:11:49
这将循环您的视频,一旦它到达终点:
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();
});<video id="testvideo" autoplay controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
如果你想早点做,你可以检查时间更新-在这种情况下,我将检查我们是否达到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();
}
});<video id="testvideo" autoplay controls>
<source src="http://techslides.com/demos/sample-videos/small.mp4" />
</video>
请记住,搜索(重置时间)总是会有一点冲动,因为数据必须被查找。唯一的解决办法是潜在地使用两个视频,并在另一个结束之前从一个视频过渡到另一个视频。下面的代码有点广泛,但实际上非常简单。
// 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;
});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;
}<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>
https://stackoverflow.com/questions/32654074
复制相似问题