JavaScript中的倒计时通常是通过设置一个未来的时间点,然后计算当前时间与这个未来时间点之间的差值,并将这个差值转换为天、小时、分钟和秒来实现的。
以下是一个简单的JavaScript倒计时示例,它可以显示距离指定日期还有多少天和小时:
function startCountdown(endDate) {
const countdownElement = document.getElementById('countdown');
function updateCountdown() {
const now = new Date().getTime();
const distance = endDate - now;
if (distance < 0) {
clearInterval(interval);
countdownElement.innerHTML = "EXPIRED";
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
countdownElement.innerHTML = `${days}d ${hours}h`;
}
updateCountdown();
const interval = setInterval(updateCountdown, 1000);
}
// 设置倒计时的结束日期和时间
const deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000); // 15天后
startCountdown(deadline);
在HTML中,你需要一个元素来显示倒计时:
<div id="countdown"></div>
localStorage
或使用服务器端逻辑来解决这个问题。为了解决页面刷新后倒计时重置的问题,可以将剩余时间存储在localStorage
中:
function startCountdownWithStorage(endDate) {
const countdownElement = document.getElementById('countdown');
let remainingTime = localStorage.getItem('remainingTime');
if (remainingTime) {
remainingTime = parseInt(remainingTime, 10);
} else {
const now = new Date().getTime();
remainingTime = endDate - now;
localStorage.setItem('remainingTime', remainingTime);
}
function updateCountdown() {
if (remainingTime < 0) {
clearInterval(interval);
countdownElement.innerHTML = "EXPIRED";
localStorage.removeItem('remainingTime');
return;
}
const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
countdownElement.innerHTML = `${days}d ${hours}h`;
remainingTime -= 1000;
localStorage.setItem('remainingTime', remainingTime);
}
updateCountdown();
const interval = setInterval(updateCountdown, 1000);
}
// 使用相同的deadline变量
startCountdownWithStorage(deadline);
这样即使用户刷新页面,倒计时也会从上次停止的地方继续。