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>
相关推荐
Andy Dennis7 分钟前
一文认识Java常见集合
java·开发语言
kyle~1 小时前
Python---Flask 轻量级Web框架
开发语言·python·flask
云深处@1 小时前
【C++11】特殊类&&单例模式
开发语言·c++
烟花落o1 小时前
算法的时间复杂度和空间复杂度
开发语言·数据结构·笔记·算法
cc.ChenLy2 小时前
【CSS进阶】毛玻璃效果与代码解析
前端·javascript·css
何中应2 小时前
使用Jenkins部署前端项目(Vue)
前端·vue.js·jenkins
西门吹-禅2 小时前
node js 性能处理
开发语言·javascript·ecmascript
我不是8神2 小时前
go-zero微服务框架总结
开发语言·微服务·golang
3秒一个大2 小时前
JWT 登录:原理剖析与实战应用
前端·http·代码规范
NEXT062 小时前
2026 技术风向:为什么在 AI 时代,PostgreSQL 彻底成为了全栈工程师的首选数据库
前端·数据库·ai编程