首页 > 解决方案 > 如何将视频的当前时间作为事件来运行&

问题描述

每个人!我是 JavaScript 新手。假设我有一个视频,并且我希望当它播放一定秒数(比如 5 秒)时,my_function 将执行(例如,应该在控制台中显示单词“五”)。出于某种原因,下面的代码正确显示了当前视频的秒数,但未在控制台中显示该单词。

html:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Text</title>

</head>
<body>
    <div class="container">
        <video width="400" controls id="video">
          <source src="video/video.mp4" type="video/mp4">
          Your browser does not support HTML5 video.
    </video>
    <span class="timelapse" id='current'> </span>
    </div>
    <button id='getTime'>getTime</button>
</body>

 <script src="js/script.js"></script>
</html>

脚本.js:

    var aud = document.getElementById('video');

aud.ontimeupdate = function(){myFunction()};

function myFunction(){
    document.getElementById('current').innerHTML = aud.currentTime;
    if (aud.currentTime == 5.0){
        console.log('Hello!');
    }
};

谢谢!

标签: javascriptjqueryhtmltimehtml5-video

解决方案


我真蠢!我将当前视频时间与特定数字(在 5.0 的示例中)进行了比较。但是,“捕获”脚本的视频的时间可能与 5.0 不同:5.1、5.121、5.132 ......并且不是整数。因此,代码不起作用。为了在控制台中显示,您需要使用:aud.currentTime > 5。所以,正确的代码是:

var aud = document.getElementById('video');

aud.ontimeupdate = function(){myFunction()};

function myFunction(){
    console.log();
    if(aud.currentTime > 5.0){
        console.log('Five')
    }
};

但现在我有另一个问题。如何让 myFunction() 只执行一次?我尝试使用这个表达式:(aud.currentTime > 5.0) & (aud.currentTime < 5.3),但不能保证。

答案就在这里


推荐阅读