下午学习了BOM,学习到定时器这块,然后仿照京东的秒杀倒计时写了一个案例。
这个是京东的倒计时。
这个是我自己写的倒计时,背景是从京东扒下来的,你也可以选择自己换个别的。
先说一下原理,获取当前时间,用输入的时间减去当前时间,得到中间差的时间,将中间差的时间做个倒计时出来。
window.setInterval(调用函数[延迟毫秒数])
是一个定时器。
是一个window对象,window可以省略不写;
第一个参数可以直接写函数名,也可以直接写函数;
第二个参数单位是毫秒数,不写默认为0;
运用Date
方法,和window.setInterval
,window.setInterval
定时器会重复调用函数,没过了后边的秒数,就会调用一次函数。
关于Date方法,倒计时的时间怎么求出来,可以参考这篇文章点我查看,当中有详细的注释,教你怎么求生时间差。
下边是代码:
<!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>
* {
margin: 0;
padding: 0;
text-decoration: none;
box-sizing: border-box;
}
a {
display: block;
border-top: 1px solid transparent;
margin: 100px auto;
width: 190px;
height: 260px;
background: url(./images/jd秒杀.png) no-repeat;
text-align: center;
color: #fff;
}
a h2 {
margin-top: 30px;
font-size: 35px;
}
a p {
margin-top: 80px;
}
a p strong {
padding: 0 10px;
font-weight: 700;
}
.hour,
.min,
.sim {
display: inline-block;
width: 30px;
height: 30px;
background-color: #001;
color: #fff;
text-align: center;
line-height: 30px;
}
.box {
margin-top: 20px;
font-weight: 700;
}
.box span {
font-weight: 900;
padding: 0 5px;
}
</style>
</head>
<body>
<a href="display:;">
<h2>半夜倒计时</h2>
<p>晚上<strong>12:00</strong>倒计时</p>
<div class="box">
<div class="hour">1</div>
<span>:</span>
<div class="min">2</div>
<span>:</span>
<div class="sim">3</div>
</div>
</a>
<script>
let hour = document.querySelector('.hour');
let min = document.querySelector('.min');
let sim = document.querySelector('.sim');
// 这个时间可以设置别的,或者用prompt来输入一个时间
let input_time = +new Date('2021-6-6 24:0:0');
// 先调用一次函数,否则刷新页面时间显示会显示空白
countDown();
// 每隔1s调用一次函数
let count_down = setInterval(countDown, 1000);
function countDown() {
let new_time = +new Date();
let times = (input_time - new_time) / 1000; // 返回时间的秒数
let h = parseInt(times / 60 / 60 % 24);
// 当时间小于10,在前边补0
h = h < 10 ? '0' + h : h;
// 将小时的数据传入到html页面中div中,下边依次是分钟和秒数
hour.innerHTML = h;
let m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
min.innerHTML = m;
let s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
sim.innerHTML = s;
}
</script>
</body>
</html>