小案例---倒计时的实现
思路如下:
- 设定目标日期的时间戳(一般从后端获取)
 - 每一秒更新一次倒计时,执行倒计时函数
 
倒计时函数内容:
- 获取时间差
 - 分别计算出对应的 天、时、分、秒
 - 更新 html 元素的内容
 
代码如下:
            
            
              html
              
              
            
          
          <div id="countdown">
  <span id="days">00</span> 天
  <span id="hours">00</span> 小时
  <span id="minutes">00</span> 分钟
  <span id="seconds">00</span> 秒
</div>
        
            
            
              js
              
              
            
          
          // 目标日期(以毫秒为单位,可以是将来的日期和时间)
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);
        
            
            
              css
              
              
            
          
          #countdown {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin: 20px;
  color: skyblue;
}
#countdown span {
  margin: 0 10px;
}