限制HTML5视频播放的次数

Asi*_*K T 10 video html5 loops

我知道我可以使用'loop'属性无限循环视频.但是我可以将视频循环的次数限制为5次吗?

Chr*_*les 23

您需要使用JavaScript来实现此目的.看看下面的代码:

var iterations = 1;

document.getElementById('iteration').innerText = iterations;

myVideo.addEventListener('ended', function () {    

    if (iterations < 5) {       

        this.currentTime = 0;
        this.play();
        iterations ++;
        
        document.getElementById('iteration').innerText = iterations;

    }   

}, false);
Run Code Online (Sandbox Code Playgroud)
<div>Iteration: <span id="iteration"></span></div>

<video width="320" height="240" id="myVideo" controls>
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
    <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />
    Your browser does not support the video tag.
</video>
Run Code Online (Sandbox Code Playgroud)

那么这里发生了什么......?

  1. 我们首先定义一个名为的变量iterations,它将存储我们当前的迭代.我们将其设置为1.
  2. 我们为myVideo视频添加了一个事件监听器,当视频结束时会触发该事件监听器.
  3. 然后我们检查iterations变量是否未超过我们的播放次数5.
  4. 我们通过重置currentTimeto 0然后使用play()函数来重启视频以启动视频.
  5. 然后我们递增iterations变量,1并且整个过程再次开始,直到我们的iterations变量到达5它停止的那一点.