如果回放结束后<video>小于30秒,我将尝试触发jquery事件。但是,我只希望此事件运行一次,无论下面的代码是通过timeupdate触发的,但它在播放结束后的30秒内重复触发任何currentTime
我怎样才能适应只跑一次?我不能简单地停止时间更新,因为我用它来显示视频的currentTime,所以这会中断。

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

最佳答案

要实现这一点,可以使用标志来跟踪事件发生的状态。默认情况下,标志将为false。只有当视频的currentTime距离结束时间少于30秒时,才会将其设置为true。
现在您可以在if条件下使用此标志,以便它只会发射一次,如下所示:

var $video = $('video');
var $p = $('p');
var eventFired = false;

$video.get(0).volume = 0.2; // just for testing

function func() {
  if (!eventFired && this.currentTime > this.duration - 30) {
    eventFired = true;
    $p.show();
  }
}

$video.on('timeupdate', func);

p { display: none; }
video {
  width: 300px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>You are less than 30 seconds from the end!</p>
<video autobuffer controls autoplay>
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>

10-06 07:46
查看更多