HTML5视频 - 如果currentTime等于设置时间,则运行事件

时间:2017-12-12 04:25:56

标签: javascript html5 javascript-events html5-video

我正在尝试在 html5 video播放时捕捉某些事件。我希望在播放期间以5,10,15,20和25秒的标记触发它们。

以下是我运行的代码:

this.video.addEventListener('timeupdate', (e) => {
  if (e.target.currentTime >= 5) {
    console.log('5 seconds')
  } else if (e.target.currentTime >= 10) {
    console.log('10 seconds')
  }
})

这似乎仅适用于第一个if语句(currentTime >= 5)。它永远不会运行else if。当我尝试准确并将>=更改为等于==的集合时,它甚至根本不运行。

我做错了什么?任何帮助将不胜感激。我也对其他更好的方法提出了建议。

我正在读这篇文章而不确定它是否合适:Syncing content with html5 video

1 个答案:

答案 0 :(得分:3)

视频越过第5秒后,第一个语句将始终为真,因为第5个句点之后的所有秒都为>=5,因此它永远不会落入else。你有两个方法

1)使用范围:

this.video.addEventListener('timeupdate', (e) => {
    if (5 <= e.target.currentTime && e.target.currentTime < 10) {
        console.log('5 seconds')
    } else if (10 <= e.target.currentTime && e.target.currentTime < 25) {
        console.log('10 seconds')
    }
});

2)反向(放置)if/else

this.video.addEventListener('timeupdate', (e) => {
    if (e.target.currentTime > 25) {
        console.log('25+ seconds')
    } else if (e.target.currentTime > 20) {
        console.log('25-20 seconds')
    } else if (e.target.currentTime > 15) {
        console.log('20-15 seconds')
    }
});