【问题标题】:JavaScript addEventListener pause and play videoJavaScript addEventListener 暂停和播放视频
【发布时间】:2018-11-06 08:49:13
【问题描述】:

我的 html 中有一个视频。我希望视频在播放后 5 秒暂停,所以我使用了 addEventListener。我还有 2 个按钮可以调用 restart() 或 jump()。

当我播放视频时,会在我的视频上调用 EventListener。它在 5 秒处暂停,但我无法在 5 秒后播放(我尝试移除监听器,但随后视频不再暂停)。当我调用 jump() 时,它会花费我 10 秒,但当我尝试播放它时会继续暂停。当我调用 reset() 时,视频将再次播放 5 秒,这是有道理的,因为我有一个 Listener。当我调用 jump() 时,如何让它在 10 秒后播放?起初我以为我必须移除我的 Listener,但我相信我仍然需要它,因为我希望视频在 15 秒处暂停。或者我可能需要在其他地方调用 removeEventListener?

js

var video = document.getElementById("myvid");
video.addEventListener("timeupdate", function(){
if(this.currentTime >= 5) {
    this.pause();       
}
});


function restart(){
    video.currentTime = 0;
}

function jump(){ 
    video.currentTime = 10; 
    if (video.currentTime >=15){
       video.pause
    }
}

html

<video id="myvid" width="320" height="240" controls>
    <source src="video.mp4" type="video/mp4">
</video>

<button onclick="restart()">restart</button>
<button onclick="jump()">jump</button>

【问题讨论】:

    标签: javascript html video addeventlistener


    【解决方案1】:

    您必须将暂停时间保存在变量中。然后就可以在跳转函数中使用了:

    var video = document.getElementById( 'myvid' ),
        pausedtime = 0;
    
    video.addEventListener( 'timeupdate', function() {
        if ( this.currentTime >= pausedtime + 5 ) {
            this.pause();
            pausedtime = this.currentTime
        }
    });
    
    function restart(){
        video.currentTime = 0;
        pausedtime = 0;
        video.play()
    }
    
    function jump(){
        pausedtime += 5;
        video.currentTime = pausedtime;
        video.play()
    }
    <video id="myvid" width="320" height="240" controls>
        <source src="http://iandevlin.com/html5/media-player/parrots.mp4.mp4" type="video/mp4">
        <source src="http://iandevlin.com/html5/media-player/parrots.webm" type="video/webm">
    </video>
    
    <br>
    
    <button type="button" onclick="restart()">Restart</button>
    <button type="button" onclick="jump()">Jump</button>

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多