HTML是網頁開發中最重要的一環,它可以實現各種實用的功能,如倒計時功能。下面將介紹如何利用HTML代碼實現倒計時功能。
<!DOCTYPE html> <html> <head> <title>倒計時功能</title> <meta charset="UTF-8"> </head> <body> <h1>倒計時</h1> <p id="demo">還剩下</p> <script> // Set the date we're counting down to var countDownDate = new Date("Jan 1, 2022 00:00:00").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "天 " + hours + "時 " + minutes + "分 " + seconds + "秒 "; // If the count down is over, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "倒計時結束!"; } }, 1000); </script> </body> </html>
以上代碼中,定義了一個countDownDate變量,用于存儲倒計時結束的日期。然后通過setInterval函數,每隔一秒鐘就更新一下距離這個時間還有多久,最終將結果輸出到id為"demo"的p標簽中。
通過上述代碼,可以輕松地實現HTML倒計時功能,讓網頁變得更加實用。