小案例---倒计时的实现

小案例—倒计时的实现

思路如下:

  1. 设定目标日期的时间戳(一般从后端获取)
  2. 每一秒更新一次倒计时,执行倒计时函数

倒计时函数内容:

  1. 获取时间差
  2. 分别计算出对应的 天、时、分、秒
  3. 更新 html 元素的内容

代码如下:

<div id="countdown">
  <span id="days">00span><span id="hours">00span> 小时
  <span id="minutes">00span> 分钟
  <span id="seconds">00span>div>

// 目标日期(以毫秒为单位,可以是将来的日期和时间)
const targetDate = new Date('2024-02-31T20:59:59').getTime();

function updateCountdown() {
  const currentDate = new Date().getTime();
  const timeRemaining = targetDate - currentDate;

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

  // 更新 HTML 元素的内容
  document.getElementById('days').innerHTML = formatTime(days);
  document.getElementById('hours').innerHTML = formatTime(hours);
  document.getElementById('minutes').innerHTML = formatTime(minutes);
  document.getElementById('seconds').innerHTML = formatTime(seconds);
}

function formatTime(time) {
  return time < 10 ? `0${time}` : time;
}

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

#countdown {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 20px;
  color: skyblue;
}

#countdown span {
  margin: 0 10px;
}

你可能感兴趣的:(小案例demo,javascript,前端,js,ecmascript)