繁体   English   中英

遇到Javascript秒表问题

[英]Having trouble with Javascript Stopwatch

我正在研制秒表,这是我的代码。 它对我来说很有意义,但不想因为某些原因而更新。

HTML:

        <ul>

            <li id="hour">0</li>
            <li>:</li>
            <li id="min">0</li>
            <li>:</li>
            <li id="sec">0</li>

        </ul>

JS:

    var sec = document.getElementById("sec").value,
        min = document.getElementById("min").value,
        hour = document.getElementById("hour").value;

        function stopWatch(){
            sec++;
            if(sec > 59) {
            sec = 0;
            min++;
            } else if(min > 59){
            min = 0;
            hour++;
            }

            window.setTimeout("stopWatch()", 1000);

        }

        stopWatch();

1)列表项LI没有值,它们具有innerHTML。

var sec = document.getElementById("sec").innerHTML; (不是.value)

2)您在代码的任何地方都没有设置 LI的内容。 JavaScript不会神奇地将ID与变量关联-您必须自己做。

如:

document.getElementById("hour").innerHTML = hour;

3)切勿将超时作为字符串传递。 使用匿名函数:

 window.setTimeout(function() {stopWatch()}, 1000);

或者,很明显:

 window.setTimeout(stopWatch, 1000);

列表项没有.value属性。 输入或textareas有。 它应该是

var sec = parseInt(document.getElementById("sec").innerHTML, 10),
    min = parseInt(document.getElementById("min").innerHTML, 10),
    hour = parseInt(document.getElementById("hour").innerHTML, 10);

这也将它们解析为数字。

另外,不要将字符串传递给setTimeout 传递您要调用的函数:

window.setTimeout(stopWatch, 1000);

您的代码中没有输出更新的变量。 它们不是DOM属性的魔术指针,只是保存数字(或原始脚本中的字符串)。

最后但并非最不重要的一点是,您的代码中存在逻辑错误。 您正在检查分钟数是否仅在秒数未超过59时才超过59。 删除else的面前if

调用应该只是

window.setInterval(stopWatch, 1000);

所以要使用秒表,把功能放在里面:

var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
    "use strict";
    sec++;
    if (sec > 59) {
        sec = 0;
        min++;
    } else if (min > 59) {
        min = 0;
        hour++;
    }
    document.getElementById("sec").innerHTML = sec;
    document.getElementById("min").innerHTML = hour;
    document.getElementById("hour").innerHTML = hour;
}, 1000);
    (function() {

        var sec = document.getElementById("sec").value,
        min = document.getElementById("min").value,
        hour = document.getElementById("hour").value;



        function stopWatch(){
            sec++;
            if(sec > 59) {
                sec = 0;
                min++;
            } else if(min > 59){
                min = 0;
                hour++;
            }
            document.getElementById("sec").textContent = sec
            document.getElementById("min").textContent = min
            document.getElementById("hour").textContent = hour
            window.setTimeout(stopWatch, 1000);
        }

        stopWatch();
    })();

Li元素没有价值属性,使用innerHTML。 您可以将sec,min和hour的值存储在变量中。 将setTimeout()调用存储到变量是一个不错的主意,以防您以后想要停止时钟。 喜欢“暂停”。

http://jsfiddle.net/chepe263/A3a9m/4/

<html>
    <head>
        <style type="text/css">
        ul li{
        float: left;
        list-style-type: none !important;

        }
        </style>
        <script type="text/javascript">//<![CDATA[ 
        window.onload=function(){

        var sec = min = hour = 0;
        var clock = 0;
        stopWatch = function(){
            clearTimeout(clock);
            sec++;
            if (sec >=59){
                sec = 0;
                min++;
            }
            if (min>=59){
                min=0;
                hour++;
            }
            document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
            document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
            document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
            clock = setTimeout("stopWatch()",1000); }
        stopWatch();
        pause = function(){
        clearTimeout(clock);
            return false;
        }

        play = function(){
            stopWatch();
        return false;
        }

        reset = function(){
            sec = min = hour = 0;
            stopWatch();
        return false;
        }           

        }//]]>  
        </script>
    </head>
    <body>
        <ul>
            <li id="hour">00</li>
            <li>:</li>
            <li id="min">00</li>
            <li>:</li>
            <li id="sec">49</li>
        </ul>
    <hr />
    <a href="#" id="pause" onClick="pause()">Pause</a>
    <a href="#" id="Play" onClick="play()">Continue</a>
    <a href="#" id="Reset" onClick="reset()">Reset</a>
    </body>
</html>

这是我的完整代码,这可能会帮助你:

<html>
<head>
    <title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
    <script language="JavaScript" type="text/javascript">
            var theResult = "";
            window.onload=function() {  document.getElementById('morefeature').style.display = 'none'; }
            function stopwatch(text) {
               var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
               document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
                if (text == "Start") {
                    document.stopwatchclock.theButton.value = "Stop";
                    document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
                    document.getElementById('morefeature').style.display = 'block';
                }
                if (text == "Stop") {
                  var jsnResult = arrAdd();
                  var cnt = 0; var op= 'jeson output';
                  for (var i = 0; i < jsnResult.length; i++) {
                      if (arr[i] !== undefined) {
                          ++cnt; /*json process*/
                          var j={ Record : cnt, Time : arr[i]};
                          var dq='"';
                          var json="{";
                          var last=Object.keys(j).length;
                          var count=0;
                          for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq;  count++;
                          if(count<last)json +=",";
                          }
                          json+="}<br>";
                          document.write(json);
                      }
                  }
              }
              if (document.stopwatchclock.theButton.value == "Start") { return true;  }
              SD=window.setTimeout("stopwatch();", 100);
              theResult = document.stopwatchclock.stpwtch.value;
              document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
            }
            function resetIt() {
                if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
                window.clearTimeout(SD);
             }
            function saveIt() {
                var value = parseInt(document.getElementById('number').value, 10);
                value = isNaN(value) ? 0 : value; value++;
                document.getElementById('number').value =  value;
                var resultTitle = '';
                if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
                var objTo = document.getElementById('stopwatchresult')
                var spanTag = document.createElement("span");
                    spanTag.id = "span"+value;
                    spanTag.className ="stopWatchClass";
                    spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration  (split time - stopwatch start time) and a lap duration (split time -  previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
                    spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
                    objTo.appendChild(spanTag);
               arrAdd(theResult);
                 return;
            }
            var arr = Array();
            function arrAdd(value){ arr.push(value); return arr;}
    </script>
    <style>
        center {
            width: 50%;
            margin-left: 25%;
        }

        .mainblock {
            background-color: #07c1cc;
        }

        .stopWatchClass {
            background-color: #07c1cc;
            display: block;
        }

        #stopwatchclock input {
            margin-bottom: 10px;
            width: 120px;
        }
    </style>
</head>
<body>
    <center>
        <div class="mainblock">
            <h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
            <form name="stopwatchclock" id="stopwatchclock">
                <input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
                <input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
                <div id="morefeature">
                    <input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
                    <input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
                    <div>
                        <input type="hidden" name="number" id="number" value="0" />
            </form>
        </div>
        <div id="stopwatchresult"></div>
    </center>
</body>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM