倒计时动态效果

227 阅读1分钟

一个很好的例子,以后会用的很多

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            margin: 100px;
        }
        
        .box div {
            width: 40px;
            height: 40px;
            float: left;
            background-color: #333;
            margin-left: 10px;
            color: #fff;
            line-height: 40px;
            text-align: center;
            font-size: 16px;
            font-weight: 700;
        }
    </style>

</head>

<body>
    <div class="box">
        <div class="hour"></div>
        <div class="minute"></div>
        <div class="second"></div>
    </div>
    <script>
        var hour = document.querySelector('.hour');
        var minute = document.querySelector('.minute');
        var second = document.querySelector('.second');
        var inputTime = +new Date('2019-8-26 18:00:00');
        countTime();
        setInterval(countTime, 1000);

        function countTime() {
            var nowTime = +new Date();
            var times = (inputTime - nowTime) / 1000;
            var h = parseInt(times / 60 / 60 % 24);
            h = h < 10 ? '0' + h : h;
            hour.innerHTML = h;
            var m = parseInt(times / 60 % 60);
            m = m < 10 ? '0' + m : m;
            minute.innerHTML = m;
            var s = parseInt(times % 60);
            s = s < 10 ? '0' + s : s;
            second.innerHTML = s;
        }
    </script>
</body>