html时钟时针转动代码

赵幸婉 3周前 15浏览 0评论

HTML时钟时针转动代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>HTML时钟时针转动代码</title>
        <style>
            .clock {
                width: 200px;
                height: 200px;
                border-radius: 50%;
                background-color: #f2f2f2;
                position: relative;
                margin: 0 auto;
            }
            .clock .hour {
                width: 6px;
                height: 60px;
                background-color: #000;
                position: absolute;
                top: 50%;
                left: 50%;
                transform-origin: bottom;
                transform: translateX(-50%) rotate(0deg);
            }
        </style>
    </head>
    <body>
        <div class="clock">
            <div class="hour"></div>
        </div>
        <script>
            var hourHand = document.querySelector('.clock .hour');
            setInterval(function() {
                var now = new Date();
                var hour = now.getHours();
                var minute = now.getMinutes();
                var second = now.getSeconds();
                var hourRotation = (hour % 12) / 12 * 360 + (minute / 60) * 30;
                hourHand.style.transform = 'translateX(-50%) rotate(' + hourRotation + 'deg)';
            }, 1000);
        </script>
    </body>
</html>

以上代码为HTML时钟的时针转动代码。

该代码使用了HTML、CSS和JavaScript实现。

CSS部分定义了时钟的基本样式,JavaScript部分获取当前的时间,并按比例计算时针的角度,然后对时针进行旋转。

该时钟代码可以用于网站的导航栏、侧边栏以及页面的任何位置,可以增加网站的交互性和美观度。