怎么创建一个数字化动态时钟?JavaScript编写代码设置小方法

济南云服务器 2026年5月21日05:13:54JavaScript怎么创建一个数字化动态时钟?JavaScript编写代码设置小方法已关闭评论41阅读模式
近日,一个位朋友问小编,自己在浏览别人的网站时,发现页面中有一个动态化的数字时钟,想要在自己的网站中也添加一个类似的功能,具体该如何编写代码实现该功能?接下来,济南网站建设小编news.hcsw666.com/就来为大家分享一个小案例,通过编写JavaScript编程代码来设置网站中数字化动态时间多的小方法,希望对大家有所帮助。
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>JS动态时钟</title>
    <style>
        body {
            background-color: #111;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .clock {
            font-size: 60px;
            color: #00eeff;
            font-weight: bold;
            letter-spacing: 5px;
            font-family: "微软雅黑";
        }
    </style>
</head>
<body>
    <div class="clock" id="clockBox"></div>

    <script>
        // 获取容器
        let clockBox = document.getElementById('clockBox');

        // 补零函数 小于10前面加0
        function addZero(num) {
            return num < 10 ? '0' + num : num;
        }

        // 获取并渲染时间
        function getTime() {
            let now = new Date();
            let h = addZero(now.getHours());
            let m = addZero(now.getMinutes());
            let s = addZero(now.getSeconds());
            // 拼接时分秒
            clockBox.innerText = `${h} : ${m} : ${s}`;
        }

        // 页面一加载先执行一次
        getTime();
        // 每秒更新一次时间
        setInterval(getTime, 1000);
    </script>
</body>
</html>

济南云服务器
  • 本文由 发表于 2026年5月21日05:13:54
  • 转载请务必保留本文链接:http://news.hcsw666.com/2765