在网页中实现视频播放时,有时我们需要让视频在特定时间段内循环播放,而不是整个视频重复播放。
这个需求可以直接用 html 标记搞定,添加三行内联事件即可。思路很简单:加载后先跳到起点,播到终点立刻拉回起点,如此往复。
- 起点跳转 :
onloadedmetadata="this.currentTime=11;this.play();"
loadedmetadata触发时,文件时长已知,设置currentTime才不会失效。 - 终点拉回 :
ontimeupdate="if(this.currentTime>=34){this.currentTime=11;this.play()}"。timeupdate大约 4~66 ms 触发一次,足够精确;到 34 s 瞬间重置,视觉无感。 - 注意去掉原生
loop:默认loop会让视频跑到结尾再重头开始,与区间逻辑冲突,直接删掉即可。
完整代码
html<video src="https://hegre-world.com/movie-taya-nude-in-cyprus/hegre-world-com-movie-taya-nude-in-cyprus-trailer-720p.mp4"preload="auto"onloadedmetadata="this.currentTime=11;this.play();"onended="this.currentTime=11; this.play();"ontimeupdate="if(this.currentTime>=17.4){this.currentTime=11;this.play()}"></video>
效果:
复制即用,兼容所有支持 <video> 的现代浏览器。若需多段循环,把判断改成数组索引即可轻松扩展。
这种方法避免了编辑视频文件的麻烦,仅通过前端代码即可实现精确的片段循环效果,为用户提供更好的观看体验。
