用原生JS实现倒计时

html部分

<div class="box">
    <h1>倒计时</h1>
    <h2>距离2020年春节还剩下</h2>
    <i><span id="newday"></span> 
    天</i>
    <i><span id="newhour"></span> 
    时</i>
    <i><span id="newminute"></span>
    分</i>
    <i><span id="newsecond"></span>
    秒</i>
</div> 

css部分

*{
            margin:0;
            padding: 0;
        }
        .box{
            width: 260px;
            height: 300px;
            background: rgb(241, 60, 60);
            margin: 100px auto;
            text-align: center;
        }
        .box>h1{
            color: aliceblue;
            font-size: 50px;
            margin-bottom: 80px;
        }
        .box>h2{
            font-size: 20px;
            color: aliceblue;
            margin-bottom: 20px;
        }
        i{
            display: inline-block;
            padding: 5px;
            /* width: 5px; */
            /* height: 45px; */
            background: #2f3430;
            text-align: center;
            line-height: 45px;
            font-style: normal;
            color: aliceblue;
            font-size: 17px;
        }

js部分

// 倒计时计算
function countDown(dateString){
    var now = new Date();
    var target = new Date(dateString);
    var difference = target.getTime() - now.getTime();
    var day = parseInt(difference /(1000 * 60 * 60 * 24)) ;
    var hour = parseInt((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minute = parseInt((difference % (1000 * 60 * 60)) / (1000 * 60));
    var second = parseInt(difference % (1000 * 60) / 1000);
    var ms = difference % 1000;
    return [
        day,
        hour,
        minute,
        second,
         ms
];
}

//加入倒计时到标签
setInterval(myCountDown,100);
myCountDown();
function myCountDown(){

   //输入目标时间
    var chunjie = countDown("2020/01/24");
    console.log(chunjie[0])
    newday.innerHTML = zeroFill(chunjie[0]);
    newhour.innerHTML = zeroFill(chunjie[1]);
    newminute.innerHTML = zeroFill(chunjie[2]);
    newsecond.innerHTML = zeroFill(chunjie[3]);
}

//个位补零
function zeroFill(num){
    if(num > 0 &&  num < 10){
        return num = "0" + num;
    }else{
        return num;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值