我正在使用以下倒计时脚本,效果很好,但我不知道如何在数字中添加前导零(例如,它显示 09 而不是 9。)有人可以帮帮我吗?这是当前脚本:
function countDown(id, end, cur){
this.container = document.getElementById(id);
this.endDate = new Date(end);
this.curDate = new Date(cur);
var context = this;
var formatResults = function(day, hour, minute, second){
var displayString = [
'<div class="stat statBig">',day,'</div>',
'<div class="stat statBig">',hour,'</div>',
'<div class="stat statBig">',minute,'</div>',
'<div class="stat statBig">',second,'</div>'
];
return displayString.join("");
}
var update = function(){
context.curDate.setSeconds(context.curDate.getSeconds()+1);
var timediff = (context.endDate-context.curDate)/1000;
// Check if timer expired:
if (timediff<0){
return context.container.innerHTML = formatResults(0,0,0,0);
}
var oneMinute=60; //minute unit in seconds
var oneHour=60*60; //hour unit in seconds
var oneDay=60*60*24; //day unit in seconds
var dayfield=Math.floor(timediff/oneDay);
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour);
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute);
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute));
context.container.innerHTML = formatResults(dayfield, hourfield, minutefield, secondfield);
// Call recursively
setTimeout(update, 1000);
};
// Call the recursive loop
update();
}