JavaScript addEventListener暂停和播放视频

时间:2018-05-27 17:43:43

标签: javascript html video addeventlistener

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

播放视频时,我的视频会调用EventListener。它会在5秒后暂停,但是我在5秒后无法播放它(我已尝试移除听众,但视频不再暂停)。当我调用jump()时,它会把我带到10秒,但是当我尝试播放它时会继续暂停。当我调用reset()时,视频将再次播放5秒钟,这是有道理的,因为我有一个监听器。当我调用jump()10秒后如何让它播放?起初我以为我必须删除我的听众,但我相信我还需要它,因为我希望视频在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>

1 个答案:

答案 0 :(得分:1)

您必须将暂停时间保留在变量中。然后你可以在跳转功能中使用它:

&#13;
&#13;
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()
}
&#13;
<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>
&#13;
&#13;
&#13;