Days
Hours
Minutes
Seconds
#countdown {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2rem;
}

.countdown-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 1rem;
}

.countdown-item span:first-child {
  font-size: 3rem;
  font-weight: bold;
}

.countdown-item span:last-child {
  font-size: 1.2rem;
  text-transform: uppercase;
  letter-spacing: 0.1rem;
}
// 目标日期
const targetDate = new Date('2022-01-01T00:00:00');

// 获取DOM元素
const daysEl = document.getElementById('days');
const hoursEl = document.getElementById('hours');
const minutesEl = document.getElementById('minutes');
const secondsEl = document.getElementById('seconds');

// 更新倒计时
function updateCountdown() {
  const now = new Date();
  const diff = targetDate - now;

  // 计算剩余天数、小时数、分钟数和秒数
  const days = Math.floor(diff / 1000 / 60 / 60 / 24);
  const hours = Math.floor((diff / 1000 / 60 / 60) % 24);
  const minutes = Math.floor((diff / 1000 / 60) % 60);
  const seconds = Math.floor((diff / 1000) % 60);

  // 更新DOM元素
  daysEl.innerText = days;
  hoursEl.innerText = hours < 10 ? '0' + hours : hours;
  minutesEl.innerText = minutes < 10 ? '0' + minutes : minutes;
  secondsEl.innerText = seconds < 10 ? '0' + seconds : seconds;
}

// 初始更新倒计时
updateCountdown();

// 每秒更新倒计时
setInterval(updateCountdown, 1000);

JS日期倒计时案例效果图

JavaScript 日期倒计时案例 - 实现网页实时倒计时效果

原文地址: https://www.cveoy.top/t/topic/mQiT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录