js如何添加时间计数器onclick事件

时间:2019-12-24 17:55:42

标签: javascript php

我正在将自定义视频播放器与html5配合使用。我已经在自定义字段中获得了视频长度,因此我很容易在播放器屏幕上标记持续时间。

我现在只需要标记一个00:00:00(代表秒,分钟和小时),当我按下视频播放器中的播放按钮时,它将开始进行累进计数。

我想我应该将命令放在以下代码行中:

playButton.addEventListener("click", function(){
     if(video.paused==true){
           video.play();
     }
}

...然后创建另一个脚本,该脚本使00:00:00受到addEventListener的影响,但是我没有足够的知识来正确地创建它。 您能帮我做吗?

1 个答案:

答案 0 :(得分:-1)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>test</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 </head>
<body>
 <div>Time <span id="time">00:00:00</span> </div>
 <div><button id="btn">pause</button></div>


 <script>

     var btn = document.getElementById("btn");
     var btnFlag = false;
     var timer = 1; // this is global variale 
 // flag means here play and pause 1 for play 0 for pause
    function startTimer(duration, display) {

        var mytimer = setInterval(function () {
        if (++timer == duration ) {
                timer--;
                clearInterval(mytimer)
            }
            $("#btn").off('click').on('click',function(e){
            //btn.addEventListener("click",function(e) {
                console.log("click")
                if(!btnFlag){
                    console.log("here")
                    btnFlag = true
                    clearInterval(mytimer)
                    $("#btn").text('Play')
                }
                else{
                    console.log("pass")
                    btnFlag = false
                    startTimer(duration, display)
                    $("#btn").text('Pause')
                }

            })

            hours  = parseInt(timer /3600, 10)
            minutes = parseInt((timer % 3600) / 60, 10)
            seconds = parseInt(timer % 60, 10);
                    hours = hours < 10 ? "0" + hours : hours;
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = hours + ":"+ minutes + ":" + seconds;


        }, 1000);

    }

    window.onload = function () {
        var timeinsecond = 100,
            display = document.querySelector('#time');
        startTimer(timeinsecond, display);
    };




 </script>
</body>
</html>

尝试