2022年的新年即將來(lái)臨,為了讓網(wǎng)頁(yè)更加生動(dòng)有趣,我們可以在網(wǎng)頁(yè)上添加一個(gè)倒計(jì)時(shí),以倒計(jì)時(shí)的方式迎接新年。下面是一個(gè)簡(jiǎn)單的HTML代碼示例,您可以將其添加到網(wǎng)站上:
<div id="countdown"> <div> <span id="days"></span> <div class="countdown-label">Days</div> </div> <div> <span id="hours"></span> <div class="countdown-label">Hours</div> </div> <div> <span id="minutes"></span> <div class="countdown-label">Minutes</div> </div> <div> <span id="seconds"></span> <div class="countdown-label">Seconds</div> </div> </div> <script> // 倒計(jì)時(shí)截止日期 var countDownDate = new Date("2023-01-01 00:00:00").getTime(); // 每1秒更新倒計(jì)時(shí) var x = setInterval(function() { // 當(dāng)前時(shí)間 var now = new Date().getTime(); // 倒計(jì)時(shí)剩余時(shí)間 var distance = countDownDate - now; // 日、時(shí)、分、秒的計(jì)算 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); // 在頁(yè)面上更新時(shí)間 document.getElementById("days").innerHTML = days + "d "; document.getElementById("hours").innerHTML = hours + "h "; document.getElementById("minutes").innerHTML = minutes + "m "; document.getElementById("seconds").innerHTML = seconds + "s "; // 當(dāng)?shù)褂?jì)時(shí)結(jié)束時(shí),更新頁(yè)面 if (distance< 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "Happy New Year!"; } }, 1000); </script>
以上代碼的核心是通過(guò)JavaScript計(jì)算倒計(jì)時(shí)的日、時(shí)、分、秒,并在頁(yè)面上更新。使用上述代碼,您可以輕松地在網(wǎng)站上添加一個(gè)新年倒計(jì)時(shí),歡迎大家嘗試!