<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.count-down-box {
overflow: hidden;
width: 190px;
height: 260px;
/* background-color: pink; */
margin: 100px auto;
background: url(images/jd.png) no-repeat top;
}
.countDownTitle {
margin-top: 40px;
font-size: 30px;
color: #fff;
text-align: center;
}
.countDownTimer {
margin-top: 100px;
color: #fff;
text-align: center;
}
.countDownContent {
margin-top: 18px;
height: 30px;
/* width: 100px; */
/* background-color: pink; */
color: #fff;
font-size: 18px;
font-weight: 700;
text-align: center;
}
.countDownContent span {
display: inline-block;
width: 30px;
height: 30px;
background-color: #2f3430;
line-height: 30px;
text-align: center;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="count-down-box">
<h2 class="countDownTitle">京东秒杀</h2>
<p class="countDownTimer">
<strong>18:00</strong> 点场 距结束
</p>
<div class="countDownContent">
<span class="count-down-hour"></span>:
<span class="count-down-minute"></span>:
<span class="count-down-second"></span>
</div>
</div>
<script>
let hour = document.querySelector(".count-down-hour");
let minute = document.querySelector('.count-down-minute');
let second = document.querySelector('.count-down-second');
// 1. 获得当前时间的时间戳
let inputTime = +new Date('2021-10-9 22:00:00');
function countDownHour() {
let nowTime = +new Date();
let timer = parseInt((inputTime - nowTime) / 1000); // 秒
let s = parseInt((timer / 60 / 60))
s = s < 10 ? '0' + s : s;
hour.innerHTML = s;
}
function countDownMinute() {
let nowTime = +new Date();
let timer = parseInt((inputTime - nowTime) / 1000)
let m = parseInt(timer / 60) % 60;
m = m < 10 ? '0' + m : m;
minute.innerHTML = m;
return m;
}
function countDownSecond() {
let nowTime = +new Date();
let timer = parseInt((inputTime - nowTime) / 1000);
let s = timer % 60;
s = s < 10 ? '0' + s : s;
second.innerHTML = s;
return s;
}
countDownHour();
countDownMinute();
countDownSecond();
let timer = setInterval(function () {
let s = countDownSecond();
if (s == 59) {
let m = countDownMinute();
if (m == 59) {
countDownHour();
}
}
}, 1000);
</script>
</body>
</html>
效果图:
调试效果图:
看到之前网上一些博主写的都是把时分秒封装到一个函数里面,然后每秒钟利用定时器回调函数将时分秒分别写入时、分、秒通过innerHTML写入span标签中,对比了一下京东原版发现有很大不同