JavaScript下班倒计时【基础】

本文深入探讨了如何使用JavaScript实现下班倒计时功能,涵盖了基础的日期和时间处理,以及定时器的运用。通过实例代码解析,帮助开发者掌握这一实用技巧。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 100px;
            background-color: rgb(128, 0, 0);
            color: white;
            text-align: center;
            line-height: 50px;
        }
        .box1 {
            width: 150px;
            height: 50px;
            background-color: green;
            margin: 0 auto;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 30px;
        }
        .box1 div {
            width: 50px;
            height: 50px;
            color: white;
        }
    </style>
</head>
<body>
    <div class="box">
        <p>下班倒计时?天</p>
        <div class="box1">
            <div class="box2">? :</div>
            <div class="box3">? :</div>
            <div class="box4">?</div>
        </div>
    </div>
    <script>
        const div = document.querySelector("div")
        // 1970.1.1毫秒

        // 时间戳三种方式
        // getTime() 必须实例化
        // +new Date
        // Date.now()
        function timer(){
            const p = document.querySelector('.box p')
            const box2 = document.querySelector('.box2')
            const box3 = document.querySelector('.box3')
            const box4 = document.querySelector('.box4')

            const future = +new Date('2023-6-6 00:00:00')
            const now = +new Date()
            const count = (future - now) / 1000

            let d = parseInt(count / 60 / 60 / 24)//总天数
            let h = parseInt(count / 60 / 60 % 24)//时
            h = h < 10 ? '0' + h : h
            let m = parseInt(count / 60 % 60)//分
            m = m < 10 ? '0' + m : m
            let s = parseInt(count % 60)//秒
            s = s < 10 ? '0' + s : s

            p.innerHTML = `下班倒计时${d}`
            box2.innerHTML = `${h}:`
            box3.innerHTML = `${m}:`
            box4.innerHTML = `${s}`
            // div.innerHTML = `还剩下${d}天${h}时${m}分${s}秒`
            // console.log(d,h,m,s);
        }
        timer()
        setInterval(timer,1000)
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值