<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>倒计时示例</title>
<style>
#countdown {
font-size: 24px;
}
#countdown span {
margin-right: 10px; /* 添加间隔 */
}
</style>
</head>
<body>
<div id="countdown">
距离到期还有:<span id="days">0</span>天 <span id="hours">0</span>小时 <span id="minutes">0</span>分钟 <span id="seconds">0</span>秒
</div>
<script>
const expiryDate = new Date(2024, 3, 2);
function updateCountdown() {
const now = new Date();
const diff = expiryDate - now;
// 防止负数出现
if (diff < 0) {
clearInterval(intervalId); // 清除定时器
document.getElementById('countdown').textContent = '已到期';
return;
}
// 计算剩余的天数、小时、分钟和秒数
const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
const diffHours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const diffMinutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
const diffSeconds = Math.floor((diff % (1000 * 60)) / 1000);
// 更新倒计时文本
document.getElementById('days').textContent = diffDays;
document.getElementById('hours').textContent = diffHours;
document.getElementById('minutes').textContent = diffMinutes;
document.getElementById('seconds').textContent = diffSeconds;
}
// 初始化倒计时显示
updateCountdown();
// 设置定时器,每秒更新一次倒计时
const intervalId = setInterval(updateCountdown, 1000);
</script>
</body>
</html>
本文含有隐藏内容,请 开通VIP 后查看