代码实现动态倒计时功能,设置目标日期为2023年9月23日,实时计算并显示剩余天数、小时、分钟和秒数,每秒更新一次。
动态时间统计
.countdown-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.countdown-timer {
text-align: center;
}
.countdown-timer h1 {
font-size: 48px;
}
.clock-icon {
animation: spin 2s linear infinite;
font-size: 48px;
margin-bottom: 20px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
// 设置目标日期和时间
const targetDate = new Date("2023-09-23T23:59:59").getTime();
// 更新倒计时的显示
function updateCountdown() {
const now = new Date().getTime();
const distance = targetDate - now;
// 计算剩余的天、小时、分钟和秒数
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
// 更新倒计时元素的内容
const countdownElement = document.getElementById("countdown");
countdownElement.innerHTML = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
// 如果目标日期已过去,则显示倒计时结束的消息
if (distance < 0) {
countdownElement.innerHTML = "倒计时结束";
}
}
// 每秒钟更新一次倒计时
setInterval(updateCountdown, 1000);