js实现倒计时

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>倒计时</title>
</head>
<body>

<p class="time-box">
    <span class="day"></span><span class="hour"></span><span class="minute"></span><span class="second"></span></p>

<p class="time-box-2">
    <span class="day"></span><span class="hour"></span><span class="minute"></span><span class="second"></span></p>

<script>
    function Countdown(elem, endTime) {
        var that = this;
        this.elems = elem.children;
        this.endTime = endTime;
        this.getTime = function () {
            var t = Date.parse(that.endTime) - Date.parse(new Date()),
                    second = Math.floor((t / 1000) % 60),
                    minute = Math.floor((t / (1000 * 60)) % 60),
                    hour = Math.floor((t / (1000 * 60 * 60)) % 24),
                    day = Math.floor(t / (1000 * 60 * 60 * 24));
            return {
                total: t,
                day: day,
                hour: hour,
                minute: minute,
                second: second
            };
        };
        this.updateTime = function () {
            var t = that.getTime(),
                    elems = that.elems;
            elems[0].innerHTML = t.day;
            elems[1].innerHTML = ("0" + t.hour).slice(-2);
            elems[2].innerHTML = ("0" + t.minute).slice(-2);
            elems[3].innerHTML = ("0" + t.second).slice(-2);
            t.total > 0 && setTimeout(that.updateTime, 1000);
        };
        this.updateTime();
    }
</script>

<script>
    new Countdown(document.querySelector(".time-box"), "2017-2-16 12:50:15");
    new Countdown(document.querySelector(".time-box-2"), "2016-12-16 19:30:00");
</script>

</body>
</html>

 

posted @ 2016-08-14 01:56  赵小磊  阅读(235)  评论(0)    收藏  举报
回到头部