0
我想創建一個倒計時器,用戶可以在其中輸入日,時,分和秒值的任意組合,並讓它倒計時完成。我覺得自己已經掌握了所有的東西,但經過一週的試圖解決這個問題,我需要幫助。我將所有的代碼隨着不同的效果進行混洗。基本上我覺得我錯過了一種方式來格式化輸入數據的方式,我可以用它來減去當前的日期,但老實說我不知道。任何輸入都會有幫助。Javascript Countdown Timer with user input
的Javascript:
function start() {
var countdownTimer = setInterval('timer()', 1000);
}
function timer() {
var d = parseInt(document.getElementById("days").value, 0);
var h = parseInt(document.getElementById("hours").value, 0);
var m = parseInt(document.getElementById("minutes").value, 0);
var s = parseInt(document.getElementById("seconds").value, 0);
var now = new Date();
var date = now.getTime();
addDay = now.setDate(now.getDate() + d);
addHour = now.setHours(now.getHours() + h);
addMinute = now.setMinutes(now.getMinutes() + m);
addSecond = now.setSeconds(now.getSeconds() + s);
var then = new Date(addHour + addMinute + addSecond);
if(d > 0 || h > 0 || m > 0 || s > 0){
var final = then - date;
var dd = Math.floor(final/ (1000 * 60 * 60 * 24));
var hh = Math.floor((final/(1000 * 60 * 60)) % 24);
var mm = Math.floor((final/1000/60) % 60);
var ss = Math.floor((final/1000) % 60);
document.getElementById("display").innerHTML = "Time Remaining: " + dd + "D " + hh + "H " + mm + "M " + ss + "S";
document.getElementById("message").innerHTML = then;
if (final < 0) {
clearInterval(countdownTimer);
document.getElementById("message").innerHTML = "Expired";
}
}else{
document.getElementById("display").innerHTML = " ";
document.getElementById("message").innerHTML = "Countdown Not Started";
}
}
HTML:
<div id="countdowntimer">
<button id="Start" onclick="start();">Start Timer</button>
D:<input type="text" id="days" value="0" />
H:<input type="text" id="hours" value="0" />
M:<input type="text" id="minutes" value="0" />
S:<input type="text" id="seconds" value="0" /><br>
<div id="display"></div>
<div id="message"></div>
</div>
謝謝。我曾考慮過這個選擇,這就是我將來會用到的。我最初想從現在的日期開始嘗試將它作爲一項挑戰,但爲了我需要的實際目的,這已經足夠了。再次感謝。 –