要求:
使用时间戳和定时器完成一个倒计时案例
效果
分析
设置一个定时器,每隔一秒刷新一次 定时器函数中显示剩余秒数转化为的时间 1. 设置两个时间戳,一个是当前的,另一个是目标时间的 2. 求出距离下班还有多少秒 3. 获取时,分,秒。并将剩余秒数转化为的时间添加到页面中 4. 修改细节
- 时间到了关定时器
- 修改当前时间
代码
<!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>
.countdown {
width: 240px;
height: 305px;
text-align: center;
line-height: 1;
color: #fff;
background-color: brown;
overflow: hidden;
}
.countdown .next {
font-size: 16px;
margin: 25px 0 14px;
}
.countdown .title {
font-size: 33px;
}
.countdown .tips {
margin-top: 80px;
font-size: 23px;
}
.countdown small {
font-size: 17px;
}
.countdown .clock {
width: 142px;
margin: 18px auto 0;
overflow: hidden;
}
.countdown .clock span,
.countdown .clock i {
display: block;
text-align: center;
line-height: 34px;
font-size: 23px;
float: left;
}
.countdown .clock span {
width: 34px;
height: 34px;
border-radius: 2px;
background-color: #303430;
}
.countdown .clock i {
width: 20px;
font-style: normal;
}
</style>
</head>
<body>
<div class="countdown">
<p class="next"></p>
<p class="title">下班倒计时</p>
<p class="clock">
<span id="hour"></span>
<i>:</i>
<span id="minutes"></span>
<i>:</i>
<span id="second"></span>
</p>
<p class="tips"></p>
</div>
<script>
let hourObj = document.querySelector('#hour')
let minuteObj = document.querySelector('#minutes')
let secondObj = document.querySelector('#second')
let next = document.querySelector('.next')
let tips = document.querySelector('.tips')
let flag
function fn() {
let d1 = + new Date()
let d2 = + new Date('2022/4/16 00:00:00')
let t = (d2 - d1) / 1000
let h = parseInt(t / 60 / 60 % 24) + ''
let m = parseInt(t / 60 % 60) + ''
let s = parseInt(t % 60) + ''
hourObj.innerHTML = h.padStart(2 , '0')
minuteObj.innerHTML = m.padStart(2 , '0')
secondObj.innerHTML = s.padStart(2 , '0')
let date = new Date()
next.innerHTML = `今天是 ${date.toLocaleDateString()}`
tips.innerHTML = `当前时间是 ${date.toLocaleTimeString()}`
if(d2 - d1 <= 0) flag = true
}
fn()
let timerId = setInterval(fn , 1000)
if(flag) {
clearInterval(timerId)
hourObj.innerHTML = '00'
minuteObj.innerHTML = '00'
secondObj.innerHTML = '00'
}
</script>
</body>
</html>
|