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

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

思路如下:

  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;
}
相关推荐
红尘散仙15 分钟前
一个 `#[uniffi::export]`,把 Rust 接进 React Native
前端·后端·rust
moshuying16 分钟前
AI Coding 最大的 token 黑洞,可能根本不是 prompt
前端
红尘散仙17 分钟前
一行 `#[specta::specta]`,让 Tauri IPC 有类型
前端·后端·rust
lichenyang45339 分钟前
HarmonyOS HMRouter 接入记录:从普通 Tab Demo 到路由跳转
前端
木斯佳1 小时前
前端八股文面经大全:腾讯WXG暑期前端一面(2026-05-15)·面经深度解析
前端·面试·笔试
canonical_entropy2 小时前
NOP Chaos Flux 架构演变史:从 AMIS 重写到现代低代码运行时
前端·aigc·ai编程
张元清2 小时前
useEffect 之外:专门处理异步、深比较和 SSR 的 Effect Hook
前端·javascript·面试
小小小小宇2 小时前
前端双Token机制无感刷新(二)
前端
XinZong3 小时前
OpenClaw 中最经典的 6 款skill,真正能进工作流的 skills
javascript·后端
zhangxingchao3 小时前
AI Agent 基础问题系统整理:从 LangChain、LangGraph、MCP 到 Agent 架构、记忆、工具调用与评估体系
前端·人工智能·后端