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>
相关推荐
leolee1816 分钟前
Redux Toolkit 实战使用指南
前端·react.js·redux
bluceli18 分钟前
React Hooks最佳实践:写出优雅高效的组件代码
前端·react.js
IT_陈寒27 分钟前
JavaScript代码效率提升50%?这5个优化技巧你必须知道!
前端·人工智能·后端
IT_陈寒28 分钟前
Java开发必知的5个性能优化黑科技,提升50%效率不是梦!
前端·人工智能·后端
LDX前端校草1 小时前
前端开发规则配置
前端
代码老中医1 小时前
2026前端工程化新范式:如何用AI驱动你的设计系统?
前端
用户11481867894841 小时前
Vite项目中的SVG雪碧图
前端·面试
这个实现不了1 小时前
vue写一些进度条样式1
前端
小蜜蜂dry1 小时前
可视化大屏适配方案之- px-To-viewport
前端
董员外2 小时前
LangChain.js 快速上手指南:Tool的使用,给大模型安上了双手
前端·javascript·后端