定时器的清除和设置:
先看效果图:
核心思路如下:
- 获取到所有单位的时间,赋值到盒子的内容
- 设定一个空对象setter 作全局变量(方便监听事件调用)
结构代码如下:
<div class="box">
<button class="start">开始倒计时</button>
<span class="days">99</span> 天
<span class="hours">99</span> 时
<span class="minutes">99</span> 分
<span class="seconds">99</span> 秒
<button class="stop">停止倒计时</button>
</div>
scirpt核心代码如下:
<script>
//获取时间框
var days = document.querySelector('.days');
var hours = document.querySelector('.hours');
var minutes = document.querySelector('.minutes');
var seconds = document.querySelector('.seconds');
//获取按钮
var start = document.querySelector('.start');
var stop = document.querySelector('.stop');
var setter = null;//设定一个空对象 作全局变量
//监听事件设置定时器
start.addEventListener('click',function () {
setter = setInterval("countDown('2021-05-26 00:00:00')",1000);//一秒调用一次
});
//监听事件清除定时器
stop.addEventListener('click',function () {
clearInterval(setter);
});
//1.获取时间戳即毫秒
//2.换算成天、时、分、秒
//3.不足10的进行补零
//4.用innerHTML添加到对于盒子
function countDown (time) {
var nowTime = +new Date();
var inputTime = +new Date(time);
var times = (inputTime - nowTime)/1000;
var d = parseInt(times / 60 / 60 / 24);
d = d < 10 ? '0' + d : d;
days.innerHTML = d;
var h = parseInt(times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
hours.innerHTML = h;
var m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
minutes.innerHTML = m;
var s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
seconds.innerHTML = s;
}
</script>
样式代码如下:
* {
padding: 0;
margin: 0;
}
.box {
width: 500px;
height: 150px;
line-height: 150px;
margin: 200px auto;
text-align: center;
background-color: lightskyblue;
border: 2px solid black;
box-shadow: 10px 10px 10px 10px gainsboro;
}
.days {
display: inline-block;
width: 50px;
height: 50px;
padding: 5px;
margin: 1px;
line-height: 50px;
font-size: 30px;
text-align: center;
background-color: black;
color: white;
}
.hours {
display: inline-block;
width: 50px;
height: 50px;
padding: 5px;
margin: 1px;
line-height: 50px;
font-size: 30px;
text-align: center;
background-color: black;
color: white;
}
.minutes {
display: inline-block;
width: 50px;
height: 50px;
padding: 5px;
margin: 1px;
line-height: 50px;
font-size: 30px;
text-align: center;
background-color: black;
color: white;
}
.seconds {
display: inline-block;
width: 50px;
height: 50px;
padding: 5px;
margin: 1px;
line-height: 50px;
font-size: 30px;
text-align: center;
background-color: black;
color: white;
}