写个还剩下多少天过年的倒计时

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>过年倒计时</title>
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f0f0f0;
        }
        #countdown {
            font-size: 2em;
            padding: 20px;
            border-radius: 10px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>

    <div id="countdown"></div>

    <script>
        function countdown() {
            const now = new Date();
            const chineseNewYear = new Date(now.getFullYear() + (now.getMonth() > 10 ? 1 : 0), 0, 1); // 注意月份是从0开始的

            const timeLeft = chineseNewYear.getTime() - now.getTime();
            const daysLeft = Math.ceil(timeLeft / (1000 * 60 * 60 * 24));

            document.getElementById("countdown").innerText = `距离${chineseNewYear.getFullYear()}年春节还有 ${daysLeft} 天!`;
        }

        countdown();
        setInterval(countdown, 1000 * 60 * 60); // 每小时更新一次
    </script>

</body>
</html>

代码解释:

  1. HTML 结构: 创建一个 div 用于显示倒计时,并设置一些基本的样式。

  2. JavaScript 逻辑:

    • countdown() 函数:

      • 获取当前时间 now
      • 计算春节日期 chineseNewYear。 这里 now.getMonth() > 10 ? 1 : 0 处理了跨年的情况。如果当前月份大于10(也就是11月或12月),那么春节就是明年的1月1日,否则就是今年的1月1日.
      • 计算时间差 timeLeft (毫秒)。
      • 计算剩余天数 daysLeft,使用Math.ceil向上取整,确保显示完整的天数。
      • 更新 countdown div 的内容,显示剩余天数。
    • setInterval(countdown, 1000 * 60 * 60):每小时调用 countdown() 函数更新倒计时。

改进建议:

  • 更精确的倒计时: 可以显示更精确的时间,例如小时、分钟和秒。
  • 更丰富的样式: 可以添加更丰富的样式,例如背景图片、动画效果等,使倒计时更美观。
  • 农历春节: 这个代码计算的是公历新年,如果需要计算农历春节,需要使用农历库或者API。

这个改进的例子包含了更精确的倒计时(天、小时、分钟、秒)和一些简单的样式:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <!-- ... (same as before) ... -->
</head>
<body>

  <div id="countdown"></div>

  <script>
    // ... (same countdown function as before, but modified below) ...

        function countdown() {
            // ... (same as before) ...

            const secondsLeft = Math.floor(timeLeft / 1000);
            const days = Math.floor(secondsLeft / (60 * 60 * 24));
            const hours = Math.floor((secondsLeft % (60 * 60 * 24)) / (60 * 60));
            const minutes = Math.floor((secondsLeft % (60 * 60)) / 60);
            const seconds = secondsLeft % 60;


            document.getElementById("countdown").innerText = `距离${chineseNewYear.getFullYear()}年春节还有 ${days}${hours}小时 ${minutes}${seconds}秒!`;
        }

        // ... (setInterval remains the same) ...
  </script>

</body>
</html>

这个例子

posted @   王铁柱6  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示