簡體   English   中英

為什么我不能增加計時器值?

[英]Why I can't increment the chronometer value?

我想要一個時間計數器,我找到了下一個代碼。 問題是我改變time = new Date(time - 1000); time = new Date(time + 1000);

這是我的代碼:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>My page</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <style>
        a{
        margin: 0 10px;
        color: gray;
        }
        .time{
            font-size: 50px;
            margin: 20px;
            font-family: monospace;
        }
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script>
        var startValue = 1000; //Number of milliseconds
        var time = new Date(startValue);
        var interv;
        $(function(){
            displayTime();
            $(".start").on("click", function(){
            interv = setInterval(function(){
                //time = new Date(time - 1000);
                time = new Date(time + 1000);
                displayTime();
            }, 1000);
            });
            $(".stop").on("click", function(){
                clearInterval(interv);
                time = new Date(startValue);
                displayTime();
            });
            $(".pause").on("click", function(){
                clearInterval(interv);
            });
            $(".reset").on("click", function(){
                time = new Date(startValue);
                displayTime();
            });
        });

        function displayTime(){
            $(".time").text(fillZeroes(time.getMinutes()) + ":" + fillZeroes(time.getSeconds()));
        }

        function fillZeroes(t){
            t += "";
            return t.length==1? "0" + t : t;
        }
    </script>
</head>
<body>
<a href="#" class="start">start</a>
<a href="#" class="stop">stop</a>
<a href="#" class="pause">pause</a>
<a href="#" class="reset">reset</a>
<div class="time"></div>
</body>
</html>

我怎么能增加時間? 謝謝!

使用date.getTime()從Date對象獲取時間戳。 在你的情況下:

time = new Date(time.getTime() + 1000);

演示: https//plnkr.co/edit/G8yo5l4wHe2yv9S3fjLI?p = preview

試試這個解決方案https://jsfiddle.net/giuseppe_straziota/eag01ojj/

$(".start").on("click", function(){
            interv = setInterval(function(){                
                                time.setSeconds(time.getSeconds() + 1);
                displayTime();
            }, 1000);
 });

問題是您嘗試將Date對象與另一個Date對象作為參數進行實例化。

var time = new Date(startValue);
...
time = new Date(time + 1000);

嘗試下次使用console.log()進行調試。

你還有一些其他問題,比如為什么你在1而不是零開始你的計數器?

這是一個應該解決所有問題的快速工作示例: https//jsfiddle.net/r6k06w40/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM