<!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>
.box {
width: 200px;
height: 100px;
margin: 200px auto;
}
span {
display: inline-block;
width: 30px;
height: 40px;
line-height: 40px;
background-color: #222;
color: #fff;
text-align: center;
font-weight: 700;
}
.banner {
position: fixed;
top: 10%;
left: 38%;
width: 300px;
height: 300px;
background-color: rgb(218, 44, 110);
font-size: 40px;
text-align: center;
line-height: 300px;
display: none;
}
</style>
</head>
<body>
<div class="box">
<span id="spanHour">01</span>
<span>:</span>
<span id="spanMin">06</span>
<span>:</span>
<span id="spanSec">15</span>
</div>
<div class="banner">秒杀开始</div>
</body>
<script>
// 需求: 倒计时秒杀
// 1. 获取元素: 时分秒
const sh = document.querySelector("#spanHour");
const sm = document.querySelector("#spanMin");
const ss = document.querySelector("#spanSec");
console.log(sh, sm, ss);
// 2. 开启定时器
let timeId = setInterval(function () {
// 2.1 获取数据: 时分秒, 转换成数字(方便计算: 安全)
let h = sh.innerText - 0;
let m = sm.innerText - 0;
let s = ss.innerText - 0;
console.log(h, m, s);
// 2.2 减小秒数
s--;
// 2.3 判定: 不能小于0, 小于0变成59, 分钟-1
if (s < 0) {
s = 59;
m--;
}
// 2.4 判定: 分钟不能小于0, 小于0变成59, 时钟 -1
if (m < 0) {
m = 59;
h--;
}
// 2.5 判定条件: 如果三个都为0, 清理定时器
if (h == 0 && m == 0 && s == 0) {
document.querySelector(".banner").style.display = "block";
clearInterval(timeId);
}
// 2.6 补0
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
// 2.7 放回元素中去
sh.innerText = h;
sm.innerText = m;
ss.innerText = s;
}, 1000);
</script>
</html>
JavaScript - WebAPI - 定时器 - 案例 - 京东倒计时秒杀
最新推荐文章于 2023-03-24 15:03:32 发布