1、需求分析
- 进入页面
1 秒之后开始倒计时,也就是1000ms
s--
s<0 s=59 m--
m<0 m=59 h--
h 、 m、 s<10 补 0 (用三元表达式或封装补零函数)
- 把数据赋值给
h m s
- 如果
h==0&&m==0&&s==0 停止计时器,移除自身
2、代码落地
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
span {
display: inline-block;
width: 80px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: red;
color: #000;
font-size: 30px;
}
strong {
font-size: 30px;
}
</style>
</head>
<body>
<div class="clock">
<span id="hour">00</span>
<strong>:</strong>
<span id="minute">01</span>
<strong>:</strong>
<span id="second">10</span>
</div>
<script>
let clock = document.querySelector('.clock')
let body = document.body
let timeID = setInterval(function () {
let h = +document.querySelector('#hour').innerHTML
let m = +document.querySelector('#minute').innerHTML
let s = +document.querySelector('#second').innerHTML
s--
if (s < 0) {
s = 59
m--
}
if (m < 0) {
m = 59
h--
}
h = h < 10 ? '0' + h : h
m = m < 10 ? '0' + m : m
s = s < 10 ? '0' + s : s
document.querySelector('#hour').innerHTML = h
document.querySelector('#minute').innerHTML = m
document.querySelector('#second').innerHTML = s
if (h == 0 && m == 0 && s == 0) {
clearInterval(timeID)
clock.style.display = 'none'
}
}, 1000)
</script>
</body>
</html>