首页 > 解决方案 > 如何检测用户距离视频结束 X 秒的时间?

问题描述

我需要检测视频何时距离总数结束 30 秒。例如,如果我的视频长度为 1 分 35 秒,我想在达到 1 分 5 秒时触发一个事件。

更新

我已经研究出如何在结束后 30 秒内的任何时间触发事件,即 30 秒、29 秒、28 秒等。问题是,下面的代码每秒重复触发,但我只希望这个事件发生一次,无论它发生在 -30s、-22s 还是 -15s。

var video = $('#video');

function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
    }
}

video.on('timeupdate', function() {
    func();
});

标签: jqueryvideo

解决方案


您可以使用文件结束事件布尔变量 - eofevent。

逻辑:开始播放时重置此变量。将其用作标志,一旦触发,请勿再次调用 func()。

var video = $('#video');
var eofevent = false; 


function func() {
    if ( video[0].currentTime > video[0].duration-30 ) {
        console.log('You are less than 30 seconds from the end!');
        eofevent = true;
    }
}

video.on('timeupdate', function() {
    if( eofevent == false )
       func();
});

video.on('play', function() {
     if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

video.on('playing', function() {
    if ( video[0].currentTime < video[0].duration ) {
        console.log('on Playing Reset!');
        eofevent = false;
    }
});

注意:我不是 jquery /javascript coder ,任何语法错误请原谅。


推荐阅读