<!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>