html实现时钟

1、html代码

 <div id="clock">
        <div>
            <span id="hours"></span>
            <span class="text">: </span>
        </div>

        <div>
            <span id="minutes"></span>
            <span class="text">: </span>
        </div>
        <div>
            <span id="seconds"></span>
            <span class="text"></span>
        </div>
    </div>

2、js代码

  function updateTime() {
        // 获取当前时间
        const now = new Date();
        // 获取小时数
        const hours = now.getHours();
        // 获取分钟数
        const minutes = now.getMinutes();

        // 获取秒数
        const seconds = now.getSeconds();

        // 格式化小时数,如果小时数小于 10,则在前面加上一个 0
        const hoursFormatted = hours < 10 ? `0${hours}` : hours;
        // 格式化分钟数,如果分钟数小于 10,则在前面加上一个 0
        const minutesFormatted = minutes < 10 ? `0${minutes}` : minutes;
        // 格式化秒数,如果秒数小于 10,则在前面加上一个 0
        const secondsFormatted = seconds < 10 ? `0${seconds}` : seconds;
        // 获取显示小时数的元素节点对象
        const hoursElem = document.getElementById('hours');
        // 获取显示分钟数的元素节点对象
        const minutesElem = document.getElementById('minutes');
        // 获取显示秒数的元素节点对象
        const secondsElem = document.getElementById('seconds');
        // 将格式化后的小时数设置为显示小时数的元素的文本内容
        hoursElem.textContent = hoursFormatted;
        // 将格式化后的分钟数设置为显示分钟数的元素的文本内容
        minutesElem.textContent = minutesFormatted;
        // 将格式化后的秒数设置为显示秒数的元素的文本内容
        secondsElem.textContent = secondsFormatted;
    }

    setInterval(updateTime, 1000);

3、css代码

   #clock {
            width: 200px;
            height: 50px;
            line-height: 50px;
            background-color: black;
            color: #fff;
            display: flex;
            justify-content: center;
        }

        #clock div {
            position: relative;
            width: 50px;
        }

        #clock div .text {
            position: absolute;
            top: 0;
            right: 10px;
            font-size: 12px;
        }
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值