如何在 JavaScript 中創建倒數計時器
本教程將演示如何在 JavaScript 中創建倒數計時器,包括一個可以復制並粘貼到自己代碼中的函數。
下面的代碼將分解創建一個計算直到某個未來時間的時間的函數,以及如何重複運行它以影響倒計時。
獲取到某個日期/時間的剩餘時間
以下函數將計算到目標日期的天、小時、分鐘和秒:
function timeToTarget(countdownString){ // Convert the string which specifies the target to count down to to a Date object let targetDate = new Date(countdownString).getTime(); // Get the current time let now = new Date().getTime(); //The getTime() method gets a millisecond representation of the time since January 1st, 1970 //Get the difference between the two let difference = targetDate - now; // Calculate the days, hours, minutes, seconds difference between the times days = Math.floor(difference / (1000 * 60 * 60 * 24)); hours = Math.floor(difference / (1000 * 60 * 60)); minutes = Math.floor(difference / (1000 * 60)); seconds = Math.floor(difference / 1000); // Calculate the result // As each of the above is the total days, hours, minutes, seconds difference, they need to be subtracted so that they add up to the correct total let result = { days: days, hours: hours - days * 24, minutes: minutes - hours * 60, seconds: seconds - minutes * 60, }; // Log the result so we can check that the function is working console.log(result); // Return the result so that it can be used outside of the function return result; }
使用 setInterval() 倒計時
JavaScript setInterval() 方法重複調用給定函數,運行之間有固定的時間延遲:
setInterval(function(){ // Code to execute repeatedly here }, 1000);
以上,函數timeToTarget() 每秒調用一次(1000 毫秒)。
顯示倒計時
要在網頁上顯示倒計時的結果,需要一個 HTML 元素:
<div id="countdown-display"></div>
然後可以使用以下 JavaScript 將倒計時信息寫入 HTML 元素:
document.getElementById("countdown-display").innerHTML = '<div>' + result.days + '<span>Days</span></div>' + '<div>' + result.hours + '<span>Hours</span></div>' + '<div>' + result.result + '<span>Minutes</span></div>' + '<div>' + result.seconds + '<span>Seconds</span></div>';
把它們放在一起
最後,需要將倒計時的日期/時間指定為字符串——這些數據可能來自日期選擇器或其他用戶輸入,或者來自數據庫:
var countdownString = "Feb 7, 2023 19:30:00";
把它們放在一起,一個工作倒計時!
var countdownString = "Feb 7, 2023 19:30:00"; function timeToTarget(countdownString){ let targetDate = new Date(countdownString).getTime(); let now = new Date().getTime(); let difference = targetDate - now; days = Math.floor(difference / (1000 * 60 * 60 * 24)); hours = Math.floor(difference / (1000 * 60 * 60)); minutes = Math.floor(difference / (1000 * 60)); seconds = Math.floor(difference / 1000); let result = { days: days, hours: hours - days * 24, minutes: minutes - hours * 60, seconds: seconds - minutes * 60, }; console.log(result); return result; } setInterval(function(){ let result = timeToTarget(countdownString); document.getElementById("countdown-display").innerHTML = '<div>' + result.days + '<span> Days</span></div>' + '<div>' + result.hours + '<span> Hours</span></div>' + '<div>' + result.minutes + '<span> Minutes</span></div>' + '<div>' + result.seconds + '<span> Seconds</span></div>' + '<div><span>Until </span>' + countdownString + '</div>'; }, 1000);