我正在用 JavaScript 构建一个倒计时时钟,并且无法完全按照我想要的方式格式化它。基本上,我有一个名为 totalTime 的变量,它最初设置为倒计时运行的总秒数。每一秒,这个数字减 1,我把它转换成分钟和秒来显示在页面上。
让我感到困惑的是,我想在剩余分钟数上包含一个前导 0,但前提是 totalTime 的初始值为 600 (10:00) 或更大。因此,如果我将 totalTime 设置为 600,我希望倒计时显示 10:00、09:59、09:58 等(注意前导 0);但如果我将 totalTime 设置为 300,我希望倒计时显示 5:00、4:59、4:58 等。
换句话说,前导 0 应该基于倒计时开始的时间量(totalTime 的初始值)出现,而不是当前剩余的时间(totalTime 的当前值)。我该怎么做?
编辑:这是我目前拥有的代码:http: //jsfiddle.net/JFYaq/
// Get the countdown element
var countdown = document.getElementById("countdown");
// Set the total time in seconds
var totalTime = 600;
// Every second...
var interval = setInterval(function(){
// Update the time remaining
updateTime();
// If time runs out, stop the countdown
if(totalTime == -1){
clearInterval(interval);
return;
}
}, 1000);
// Display the countdown
function displayTime(){
// Determine the number of minutes and seconds remaining
var minutes = Math.floor(totalTime / 60);
var seconds = totalTime % 60;
// Add a leading 0 to the number of seconds remaining if it's less than 10
if (seconds < 10){
seconds = "0" + seconds;
}
// Split the number of minutes into two strings
var minutesString = minutes + "";
var minutesChunks = minutesString.split("");
// Split the number of seconds into two strings
var secondsString = seconds + "";
var secondsChunks = secondsString.split("");
// If the total time is 10 minutes or greater...
if (totalTime >= 600){
// Add a leading 0 to the number of minutes remaining if it's less than 10
if (minutes < 10){
minutes = "0" + minutes;
}
// Display the time remaining
countdown.innerHTML = "<span>" + minutesChunks[0] + "</span>" + "<span>" + minutesChunks[1] + "</span>" + ":" + "<span>" + secondsChunks[0] + "</span>" + "<span>" + secondsChunks[1] + "</span>";
}
// If the total time is less than 10 minutes...
else {
// Display the time remaining without a leading 0 on the number of minutes
countdown.innerHTML = "<span>" + minutes + "</span>" + ":" + "<span>" + secondsChunks[0] + "</span>" + "<span>" + secondsChunks[1] + "</span>"
}
}
// Update the time remaining
function updateTime(){
displayTime();
totalTime--;
}
// Start the countdown immediately on the initial pageload
updateTime();