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

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

思路如下:

  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;
}
相关推荐
hunterandroid14 分钟前
HarmonyOS HUKS 密钥全生命周期实战:生成、轮换与失效处理
前端·华为
damoluomu16 分钟前
SSG 的后台怎么补:Node.js 生态里的三条路(番外二)
javascript·css·typescript·node.js·html
东鹏特饮23 分钟前
贪吃蛇小游戏html
前端·javascript·html
溪语流沙25 分钟前
【每天一个CSS | Day23】边框上有一道光在跑的流光呼吸卡片
前端·css
小马不起床27 分钟前
零基础玩转 FastAPI_10:前端登录、权限与布局
前端·状态模式·fastapi
程序员Sunday34 分钟前
JavaScript 深拷贝和浅拷贝有什么区别?structuredClone 能替代 JSON 拷贝吗?
前端·javascript
ShineWinsu1 小时前
对于CSS:选择器的解析
前端·css·面试·html·web·选择器·网页
m0_587383001 小时前
碰碰好评卡功能落地实战 从需求梳理到上线部署全流程实操指南
java·linux·服务器·前端·javascript·vue.js·人工智能
Pu_Nine_91 小时前
Vue‑Flow 从零入门实战|AI‑Agent 拓扑图开发
前端·javascript·vue.js
keyipatience1 小时前
CSS 学习(1):语法、引入方式、选择器、字体与背景
前端·css·html