思路: 先写3个盒子 然后查找元素 3个盒子分别存放时 分 秒 3个盒子利用innerHTML放入计算的小时、分钟、秒数 第一次执行间隔毫秒数 所以刚刚刷新的时候页面会有空白 用函数封装 先调用一次这个函数 防止开始时页面刷新时出现空白 倒计时是不断变化的,所以用到定时器 (setInterval) 然后把写好的倒计时调用即可。
<!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>京东倒计时效果</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 300px;
border: 1px solid #000;
background: url(https://misc.360buyimg.com/mtd/pc/index_2019/1.0.0/assets/img/4a15d8883775742e3efbb850ae14def7.png) no-repeat center;
background-size: 100% 100%;
}
p {
color: #fff;
font-size: 26px;
font-weight: 700;
text-align: center;
margin-top: 40px;
}
.box1-item {
color: #fff;
font-size: 14px;
}
.box1-item>strong {
font-size: 18px;
}
.box1 {
margin-top: 120px;
text-align: center;
}
.hour,
.minute,
.second {
display: inline-block;
width: 30px;
height: 30px;
line-height: 30px;
border: 1px solid #000;
background-color: #2f3430;
}
.box1-item2 {
display: block;
margin-top: 15px;
font-size: 18px;
color: #fff;
font-weight: 700;
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<div class="box">
<p>京东秒杀</p>
<div class="box1">
<div class="box1-item">
<strong>22:00</strong>
点场 距结束
</div>
<span class="box1-item2">
<span class="hour">1</span>
<span> : </span>
<span class="minute">2</span>
<span> : </span>
<span class="second">3</span>
</span>
</div>
</div>
<script>
// 获取元素
var hour = document.querySelector('.hour');
var minute = document.querySelector('.minute');
var second = document.querySelector('.second');
var inputTime = +new Date('2021-12-23 10:00:00');////返回的是用户输入时间总的毫秒数
// 开启定时器
countDown();//我们先调用一次这个函数,防止第一次刷新时页面空白。
setInterval(countDown, 1000)
function countDown(time) {
var nowTime = +new Date(); //返回的是当前时间总的毫秒数
// var inputTime = +new Date(time);//返回的是用户输入时间总的毫秒数
var times = (inputTime - nowTime) / 1000;//times剩余时间总的毫秒数
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>
</html>