Skip to content

Project 03: 全屏时钟 (JS)

完整代码

html
<!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 {
            margin: 0;
            padding: 0;
            font-size: 30vw;
            font-family: Consolas;
            color: white;
        }

        .time {
            --percent: 0%;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background-image: linear-gradient(to right, #006400, #006400 calc(var(--percent) - 1%), #004B00 calc(var(--percent) + 1%));
        }
    </style>
</head>
<body>

<div id="app" class="time"></div>

<script>
    const appElement = document.getElementById('app');

    function pad(n) {
        return n < 10 ? `0${n}` : `${n}`;
    }

    function updateTime() {
        const now = new Date();
        const seconds = now.getSeconds();
        const minutes = now.getMinutes();
        const hours = now.getHours();

        const percent = (seconds / 60 * 100).toFixed(2) + '%';
        const timeString = `${pad(hours)}:${pad(minutes)}`;

        appElement.textContent = timeString;
        appElement.style.setProperty('--percent', percent);
    }

    setInterval(updateTime, 335);

    // Initial call to set the time immediately on page load
    updateTime();
</script>

</body>
</html>

Built by Vitepress | Apache 2.0 Licensed