您可能在想为什么不直接使用 html 的视频循环来循环播放视频。问题是当我循环播放视频时,它并不流畅和无缝。我尝试寻找其他解决方案,但没有找到。因此,我尝试让视频在结束(或接近结束)时跳回开头。
如何使用 JavaScript 执行此操作?
<video autoplay id="testvideo" width="100%" height="900px">
<source src="examplevideo.mp4" type="video/mp4" />
</video>
最佳答案
这将在视频结束后循环播放:
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>
如果您想早点执行此操作,可以检查 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();
}
});
<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>
关于javascript - 如何使用javascript使视频结束后跳回开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654074/