<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#box {
width: 300px;
height: 200px;
margin: 200px auto;
text-align: center;
}
p {
color: orange;
}
strong {
color: white;
display: inline-block;
margin: 0 5px;
padding: 2px 5px;
background-color: orange;
border-radius: 5px;
font-weight: bold;
}
</style>
<script src="js/common.js"></script>
</head>
<body>
<div id="box">
<h4>距离考试还有</h4>
<p><span><span id="day">0</span>天</span><strong><span id="hour">0</span>时</strong><strong><span id="minute">0</span>分</strong><strong><span id="second">0</span>秒</strong></p>
</div>
<script>
var endDate = new Date('2021-10-1 0:0:0'); // 目标时间
var spanDay = my$('day');
var spanHour = my$('hour');
var spanMinute = my$('minute');
var spanSecond = my$('second');
// setInterval(function () {
// var startDate = new Date(); // 当前时间
// var inteval = getInterval(startDate, endDate);
// setInnerText(spanDay, inteval.day);
// setInnerText(spanHour, inteval.hour);
// setInnerText(spanMinute, inteval.minute);
// setInnerText(spanSecond, inteval.second);
// }, 1000); // 刷新时会先显示0分0秒,因为隔1秒才执行setInterval
setInterval(countdown, 1000);
countdown(); // 页面加载完成先调用一次,再隔1秒执行
function countdown() {
var startDate = new Date(); // 当前时间
var inteval = getInterval(startDate, endDate);
setInnerText(spanDay, inteval.day);
setInnerText(spanHour, inteval.hour);
setInnerText(spanMinute, inteval.minute);
setInnerText(spanSecond, inteval.second);
}
</script>
</body>
</html>
// common.js
// innerText textContent 兼容性处理
function setInnerText(element, content) {
if (typeof element.innerText === 'string') {
element.innerText = content;
} else {
element.textContent = content;
}
}
// 获取两个日期的时间差
function getInterval(start, end) {
// 两个日期对象相差的毫秒数
var interval = end - start;
var day, hour, minute, second;
// 两个日期对象相差的秒数
interval /= 1000;
day = Math.round(interval / 60 / 60 / 24);
hour = Math.round(interval / 60 / 60 % 24); // 去除天数剩下的才是小时数
minute = Math.round(interval / 60 % 60);
second = Math.round(interval % 60);
return {
day: day,
hour: hour,
minute: minute,
second: second
}
}