我正在尝试创建一个倒数计时器,用户可以输入日,小时,分钟和秒值的任意组合,并让倒计时完成。我觉得我已经掌握了所有的部分,但经过一周的努力解决这个问题,我需要帮助。我用各种不同的效果来乱码。基本上我觉得我错过了一种格式化输入数据的方法,我可以用它来减去当前日期,但老实说我不知道。任何输入都会有所帮助。
使用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>
答案 0 :(得分:0)
如果您的计时器不是基于日期,而是基于给定的天数,小时数,分钟数和秒数,为什么要包含日期? <怎么样
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 current = ((d * 86400) + (h * 3600) + (m * 60) + s); //the current time left in seconds
if (current > 0) {
//take one second away, and rerender the seconds split into d, h, m, and s in the html, which you will reuse next time timer() runs
} else {
//expired
}
}