0

我需要帮助制作倒数计时器!

用户在文本字段中输入一个值,当一个按钮被点击时计时器开始计时。

计时器文本每秒递减一,直到达到零。

我有第一步的代码,但似乎无法让第二步工作。我知道它需要包含一个 setTimeout 和循环。

继承人到目前为止的代码:

HTML-

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


</head>
<body>



<div id="form">

<h2> COUNTDOWN</h2>

    Seconds: <input type="text" name="seconds" id="seconds" /> <input type="button" value="Start!" id="start" /> <input type="button" value="Pause" id="pause"  />
</div>


<div id="info">


</div>


<div id="countdown">


</div>

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

JAVASCRIPT-

window.onload = function(){

var startButton = document.getElementById("start");

var form = document.getElementById("seconds");

var pause = document.getElementById("pause");

var secDiv = document.getElementById("countdown");

var editSec = document.createElement("h1");


startButton.onclick = function (){

editSec.innerHTML = form.value;
secDiv.appendChild(editSec);


};


};
4

4 回答 4

1

它是这样的:

var globalTime = form.value; //receive the timer from the form
var secDiv = document.getElementById("countdown");

function decreaseValue() {
  globalTime = globalTime - 1;

   secDiv.innerHTML = globalTime;
}

startButton.onclick = function (){
  setTimeout(decreasValue(),1000);
};

//clear out the timers once completed
于 2013-03-04T15:40:56.450 回答
0

您需要使用 setInterval,而不是 setTimeout。将此代码添加到 onclick 函数中:

editSec.id = "editSec";
window.cdint = setInterval(function(){ 
    var origVal = parseInt(document.getElementById("editSec").innerHTML);
    document.getElementById("editSec").innerHTML = origVal - 1;
    if(origVal - 1 <= 0){
        window.cdint = clearInterval(window.cdint);
    }
}, 1000);
于 2013-03-04T15:37:10.097 回答
0

使用setInterval

var time = 100;
var countdown = function(){
    secdiv.innerHTML = time;
    time--;
}
setInterval(countdown,1000);
于 2013-03-04T15:37:44.107 回答
0

如果需要,您可以使用setTimeout

startButton.onclick = function () {
    var value = parseInt(form.value);
    editSec.innerHTML = value;
    secDiv.appendChild(editSec);
    setTimeout(function () {
        editSec.innerHTML = --value < 10
            ? '<span style="color:red">' + value + '</span>'
            : value;
        if (value) {
            setTimeout(arguments.callee, 1000);
        }
    }, 1000);
};
于 2013-03-04T15:51:33.860 回答