<!DOCTYPE html> <html> <head> <title>倒计时页面</title> <style> #countdown { font-size: 48px; color: #000; } </style> </head> <body> <h1>倒计时页面</h1> <label for="date">输入日期:</label> <input type="date" id="date"> <button onclick="startCountdown()">开始倒计时</button> <h2 id="countdown"></h2> <script> function startCountdown() { var inputDate = document.getElementById("date").value; var countdownElement = document.getElementById("countdown"); var countdownDate = new Date(inputDate).getTime(); var x = setInterval(function () { var now = new Date().getTime(); var distance = countdownDate - now; 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); countdownElement.innerHTML = days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒 "; var randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16); countdownElement.style.color = randomColor; if (distance < 0) { clearInterval(x); countdownElement.innerHTML = "倒计时已结束"; countdownElement.style.color = "#000"; } }, 1000); } </script> </body> </html>
复制
这个页面包含一个输入日期的输入框、一个“开始倒计时”的按钮以及一个显示倒计时的元素。当用户点击按钮时,会通过JavaScript获取输入的日期,并开始一个定时器,每秒更新倒计时并随机改变颜色。当倒计时结束时,定时器会被清除,倒计时元素将显示"倒计时已结束",颜色会恢复为黑色。
希望这个示例能帮到你!