<video>结束时显示消息</video>

时间:2013-04-27 04:33:37

标签: javascript html5-video

之前可能已经回答了这个问题,但是我已经搜索了几个小时,但是如果没有jquery就找不到任何工作,我真的不懂绑定方法或者它是如何工作的。

我只需要我的视频在完成后显示一条消息。 出于某种原因,任何时候我尝试使用video.ended我得到null而不是true或false。 也不确定为什么我的setInterval显然是错误的。

HTML:

<video id="videoAllUrBase" poster="images/all-ur-base-poster.png">
    <source src="video/All Your Base Are Belong To Us.mp4" />
    <source src="video/All Your Base Are Belong To Us.mp4.ogg" />
    <source src="video/All Your Base Are Belong To Us.mp4.webm" />
    <p>Your browsers does not support video</p>
</video>
<br></br>
<input id="playButton" type="button" onclick="playVideo();" value="Play" />
<input id="skipButton" type="button" onclick="skip(10);" value="Skip" />
<input id="rewButton" type="button" onclick="skip(-10);" value="Rewind" />
<p id="vidMessage">Click the Play button to start the video.</p>

JavaScript的:

function playVideo(){
    var video = document.getElementById('videoAllUrBase');
    var message = document.getElementById('vidMessage');
    var button = document.getElementById('playButton');

    if(video.paused){
        video.play();
        button.value = "Pause";
        message.innerHTML = "The video is playing, click the Pause button to pause the video.";
    } else {    
        video.pause();
        button.value = "Play";
        message.innerHTML = "The video is paused, click the Play button to resume the video.";
    } 

}

function checkEnd{
    var video = document.getElementById('videoAllUrBase');
    var message = document.getElementById('vidMessage');

    if(video.ended){
        message.innerHTML = "The video has ended, click Play to restart the video.";
    }
}

setInterval(checkEnd, 1000);

function skip(value) {
    var video = document.getElementById("videoAllUrBase");
    video.currentTime += value;
}   

1 个答案:

答案 0 :(得分:1)

不要使用setInterval来检查视频的状态,而是监听ended事件以了解其结束时间。这是您使用我所使用的更改的代码:

function playVideo() {
    var video = document.getElementById('videoAllUrBase');
    var message = document.getElementById('vidMessage');
    var button = document.getElementById('playButton');

    if (video.paused) {
        video.play();
        button.value = "Pause";
        message.innerHTML = "The video is playing, click the Pause button to pause the video.";
    } else {    
        video.pause();
        button.value = "Play";
        message.innerHTML = "The video is paused, click the Play button to resume the video.";
    }

    video.onended = videoEnded;
}

function videoEnded() {
    var video = document.getElementById('videoAllUrBase');
    var message = document.getElementById('vidMessage');
    message.innerHTML = "The video has ended, click Play to restart the video.";
}

function skip(value) {
    var video = document.getElementById("videoAllUrBase");
    video.currentTime += value;
}

虽然它可能不会影响您的设置,但使用addEventListener绑定事件可能更有用。

参考文献: