用原生JS实现倒计时

html部分

倒计时

距离2020年春节还剩下

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;

    }

}

你可能感兴趣的:(用原生JS实现倒计时)