html css js 实现简易时钟

 基本思路:

        1. 通过日期对象获取当前时间

        2. 利用getHours, getMinutes, getSeconds获取当前的时分秒

        3. 分针的位置 = rotate(当前分钟*6 deg)

        4. 秒针的位置 = rotate(当前秒数*6 deg)

        5. 时针的位置 = rotate(当前小时*30 deg)

        6. 利用setInterval每秒钟重新移动一次时分秒针的位置

以下是html和js代码 


<body>
    <div> <!--表盘盒子-->
        <span></span>  <!--秒针盒子-->
        <b></b>  <!--分针盒子-->
        <i></i>  <!--时针盒子-->
        <em></em>  <!--表盘中心圆点-->
    </div>

    <script>
        // 获取时分秒表针
        let sec = document.querySelector('span') 
        let min = document.querySelector('b') 
        let hour = document.querySelector('i') 
        
        // 利用日期对象获取当前时分秒,将时分秒转化为指针的旋转度数
        let timeChange = function () {
            let timer = new Date() 
            let s = timer.getSeconds()
            let m = timer.getMinutes()
            let h = timer.getHours()
            h = h > 12 ? h-12 : h 
            sec.style.transform = `rotate(${s*6}deg)`
            min.style.transform = `rotate(${m*6}deg)`
            hour.style.transform = `rotate(${h*30}deg)`
        }        

       // 用setInterval函数每秒钟重绘一次指针
        setInterval(timeChange, 1000)
    </script>
</body>

以下是css代码

    div {
            position: relative;
            width: 100px;
            height: 100px;
            background: #fff;
            border-radius: 50%;
            border: 6px solid #000;
        }

        span {
            position: absolute;
            left: 50%;
            transform: translate(-50%);
            top: 10px;
            width: 3px;
            height: 40px;
            background-color: #000;
            transform-origin: bottom;
        }

        b {
            position: absolute;
            left: 50%;
            transform: translate(-50%);
            top: 15px;
            width: 4px;
            height: 35px;
            background-color: red;
            transform-origin: bottom;
        }

        i {
            position: absolute;
            left: 50%;
            transform: translate(-50%);
            top: 20px;
            width: 5px;
            height: 30px;
            background-color: blueviolet;
            transform-origin: bottom;
        }

        em {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #000;
        }
  

以下是运行效果:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值