我正在JavaScript中構建倒數計時器,並且無法準確格式化它。基本上,我有一個名爲totalTime的變量,它最初設置爲倒計時運行的總秒數。每秒鐘,這個數字減1,我將它轉換成分鐘和秒數,以便在頁面上顯示。在JavaScript中構建倒數計時器
讓我感到沮喪的是,我希望在剩餘分鐘數中包含前導0,但前提是初始值 totalTime爲600(10:00)或更大。所以,如果我將totalTime設置爲600,我希望倒數顯示爲10:00,09:59,09:58等(注意前導0);但如果我將totalTime設置爲300,我希望倒數顯示爲5:00,4:59,4:58等。
換言之,根據倒數開始的時間量顯示前導0 off(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();
你可以發佈你寫的代碼? –
更新了JSFiddle的鏈接(出於某種原因,我無法在文章中正確格式化代碼)。 – daGUY