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>
相关推荐
WJ.Polar5 分钟前
Python数据容器-list和tuple
开发语言·python
幼儿园技术家6 分钟前
Uniapp简易使用canvas绘制分享海报
前端
FrostedLotus·霜莲19 分钟前
C++主流编辑器特点比较
开发语言·c++·编辑器
超级码.里奥.农21 分钟前
零基础 “入坑” Java--- 七、数组(二)
java·开发语言
KENYCHEN奉孝30 分钟前
Rust征服字节跳动:高并发服务器实战
服务器·开发语言·rust
挺菜的38 分钟前
【算法刷题记录(简单题)002】字符串字符匹配(java代码实现)
java·开发语言·算法
开开心心就好1 小时前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑
全宝1 小时前
🎨前端实现文字渐变的三种方式
前端·javascript·css
yanlele1 小时前
前端面试第 75 期 - 2025.07.06 更新前端面试问题总结(12道题)
前端·javascript·面试
妮妮喔妮2 小时前
【无标题】
开发语言·前端·javascript