【问题标题】:HTML5 pause a video at certain pointsHTML5 在某些点暂停视频
【发布时间】:2018-08-29 16:17:03
【问题描述】:

我有一个视频,我想根据视频的当前时间在几个不同的时间点暂停它。将有 3 个站点,5 秒 1 个,10 秒 1 个,15 秒 1 个。在每一站,都会出现一个按钮以继续播放视频。我不确定如何进行这项工作,因为currentTime 从来没有准确地达到这些点,所以目前我必须使用>= 时间停止,这意味着 5 秒停止点将连续触发。

var video = $('#video').get(0);

video.addEventListener('timeupdate', function() {
    if(this.currentTime >= 5) {
        console.log('5 seconds');
        this.pause();
        $('button').css('display','block');
    }
    
    if(this.currentTime >= 10) {
      console.log('10 seconds');
      this.pause();
      $('button').text('Part 3');
      $('button').css('display','block');
    }
    
    if(this.currentTime >= 15) {
      console.log('15 seconds');
      this.pause();
      $('button').text('Part 4');
      $('button').css('display','block');
    }
});

$('button').click(function() {
  video.play();
  $('button').css('display','none');
});
button {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="video" autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>

<button>Part 2</button>

【问题讨论】:

  • 您是否要在您的视频中投放广告?
  • 不,我只是想在页面上添加一些关于视频每个片段的详细信息并暂停视频,以便用户在继续下一个片段之前查看这些详细信息。

标签: javascript jquery html5-video


【解决方案1】:

正如您所见,timeupdate 并不总是在 精确 间隔。它可以是几毫秒。

要解决您遇到的问题,您可以存储一个变量,该变量保存视频中发生timeupdate 的最后一点,并将其包含在您的if 条件中:

var $video = $('#video');
var video = $video.get(0);

video.addEventListener('timeupdate', function() {
  var lastCheckedAt = $video.data('lastcheck') || 0;
  $video.data('lastcheck', this.currentTime);
  
  if (this.currentTime >= 5 && lastCheckedAt < 5) {
    console.log('5 seconds');
    this.pause();
    $('button').show();
  } else if (this.currentTime >= 10 && lastCheckedAt < 10) {
    console.log('10 seconds');
    this.pause();
    $('button').text('Part 3').show();
  } else if (this.currentTime >= 15 && lastCheckedAt < 15) {
    console.log('15 seconds');
    this.pause();
    $('button').text('Part 4').show();
  }
});

$('button').click(function() {
  video.play();
  $('button').hide();
});
button {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4">
</video>

<button>Part 2</button>

还要注意使用show()hide() 而不是直接调用css()

【讨论】:

  • 非常酷,感谢您的解决方案,这正是我所需要的!
  • 没问题,很高兴为您提供帮助。我还刚刚对逻辑进行了另外几个调整。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2012-05-06
  • 1970-01-01
  • 2019-01-09
  • 2016-07-31
  • 1970-01-01
相关资源
最近更新 更多