HTML5 在某些点暂停视频

use*_*286 4 javascript jquery html5-video

我有一个视频,我想根据视频的当前时间在几个不同的点暂停它。将有 3 次停止,一次在 5 秒时,一次在 10 秒时,一次在 15 秒时。每次停止时,都会出现一个按钮以继续播放视频。我不确定如何进行这项工作,因为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');
});
Run Code Online (Sandbox Code Playgroud)
button {
  display:none;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

正如您所见,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();
});
Run Code Online (Sandbox Code Playgroud)
button {
  display: none;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

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

  • 没问题,很高兴为您提供帮助。我还刚刚对逻辑进行了一些调整。 (2认同)