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

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

思路如下:

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

倒计时函数内容:

  1. 获取时间差
  2. 分别计算出对应的 天、时、分、秒
  3. 更新 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;
}
相关推荐
WHOVENLY21 小时前
【javaScript】- 笔试题合集(长期更新,建议收藏,目前已更新至31题)
开发语言·前端·javascript
指尖跳动的光1 天前
将多次提交合并成一次提交
前端·javascript
程序员码歌1 天前
短思考第263天,每天复盘10分钟,胜过盲目努力一整年
android·前端·后端
oden1 天前
1 小时速通!手把手教你从零搭建 Astro 博客并上线
前端
若梦plus1 天前
JS之类型化数组
前端·javascript
若梦plus1 天前
Canvas 深入解析:从基础到实战
前端·javascript
若梦plus1 天前
Canvas渲染原理与浏览器图形管线
前端·javascript
C_心欲无痕1 天前
vue3 - 依赖注入(provide/inject)组件跨层级通信的优雅方案
前端·javascript·vue.js
幺零九零零1 天前
全栈程序员-前端第二节- vite是什么?
前端