【问题标题】:HTML5 Video run event once if currentTime is larger than X如果 currentTime 大于 X,则 HTML5 视频运行事件一次
【发布时间】:2019-11-11 11:18:11
【问题描述】:

如果<video> 距离播放结束不到 30 秒,我将尝试触发 jquery 事件。但是,我只希望这个事件运行一次,无论

我有以下通过 timeupdate 触发的代码,但它会在播放结束后 30 秒内重复触发任何currentTime

如何调整为只运行一次?我无法简单地停止 timeUpdate,因为我使用它来显示视频的 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();
});

【问题讨论】:

  • 嗨,Rory,您介意将其转换为答案吗,不确定我是否 100% 关注?
  • 好的,我给你加了
  • 谢谢罗里,太完美了:)

标签: jquery html video


【解决方案1】:

要实现这一点,您可以使用标志来跟踪事件发生的状态。默认情况下,该标志将为假。仅当视频的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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多