html实现倒计时

参考网址

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>倒计时示例</title>
</head>
<body>
  <h1 id="titleCountDown"></h1>
  <div id="countdown"></div>

  <script>
    // 目标日期
    var targetDate = new Date("2024-10-11T15:40:00");
    const year = targetDate.getFullYear();
    const month = targetDate.getMonth() + 1;
    const day = targetDate.getDate();
    const hours = targetDate.getHours();
    const minutes = targetDate.getMinutes();
    const seconds = targetDate.getSeconds();
    document.getElementById("titleCountDown").innerHTML = `距离${year}-${month}-${day} ${hours}:${minutes}:${seconds}还有:`

    var timer = null;
    // 更新倒计时
    function updateCountdown() {
      var now = new Date();
      var timeLeft = targetDate - now;
      if (timeLeft < 0) {
        document.getElementById("countdown").innerHTML = "时间已过";
        return;
      }

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

      // 更新页面上的倒计时显示
      document.getElementById("countdown").innerHTML = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";

      // 每秒钟更新一次倒计时
      timer && clearTimeout(timer);
      timer = setTimeout(updateCountdown, 1000);
    }

    // 启动倒计时
    updateCountdown();
  </script>
</body>
</html>
相关推荐
翻滚吧键盘30 分钟前
{{ }}和v-on:click
前端·vue.js
上单带刀不带妹36 分钟前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
杨进军1 小时前
React 创建根节点 createRoot
前端·react.js·前端框架
ModyQyW1 小时前
用 AI 驱动 wot-design-uni 开发小程序
前端·uni-app
-凌凌漆-1 小时前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼1 小时前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
说码解字1 小时前
Kotlin lazy 委托的底层实现原理
前端
军训猫猫头2 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
爱分享的程序员2 小时前
前端面试专栏-算法篇:18. 查找算法(二分查找、哈希查找)
前端·javascript·node.js
翻滚吧键盘2 小时前
vue 条件渲染(v-if v-else-if v-else v-show)
前端·javascript·vue.js