持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第20天,点击查看活动详情
布局:
<div id="div1">
<div id="div2">
<ul>
<li>
<h1>淘宝11.11</h1>
</li>
<li>TAO BAO</li>
<li>⚡</li>
<li>双十一倒计时</li>
</ul>
<span id="z">1</span>
<p id="p1">天</p>
<span id="a">1</span>
<p id="p2">时</p>
<span id="b">2</span>
<p id="p3">分</p>
<span id="c">3</span>
<p id="p4">秒</p>
</div>
</div>
样式:
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
#div1 {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#div2 {
background-color: pink;
width: 180px;
height: 240px;
display: flex;
justify-content: center;
position: relative;
}
span {
background-color: black;
color: white;
width: 30px;
height: 25px;
display: block;
text-align: center;
position: absolute;
top: 170px;
}
#a {
left: 55px;
}
#b {
left: 95px;
}
#c {
right: 15px;
}
li {
color: white;
}
li:nth-of-type(1) {
margin-top: 40px;
}
ul {
text-align: center;
}
#z {
left: 15px;
}
p {
position: absolute;
top: 200px;
}
#p4 {
right: 22px;
}
#p3 {
left: 100px;
}
#p2 {
left: 60px;
}
#p1 {
left: 20px;
}
</style>
先获取4个span标签
let z = document.querySelector('#z')
let a = document.querySelector('#a')
let b = document.querySelector('#b')
let c = document.querySelector('#c')
双十一的时间戳
let d = +new Date('2022-11-11 00:00:00')
调用fn()是因为如果不单独调用1次页面需要1秒后才能刷新出我们想要的效果
fn()
每隔1秒调用一次函数
setInterval(fn, 1000)
function fn() {
当前时间戳
let nowtime = +new Date()
双十一时间-现在时间/1000毫秒
let date = (d - nowtime) / 1000 距离当前的秒
let day = parseInt(date / 60 / 60 / 24)
day = day < 10 ? '0' + day : day
z.innerHTML = day
let hour = parseInt(date / 60 / 60 % 24)
hour = hour < 10 ? '0' + hour : hour //如果小于10就在前面加0,否则就是正常数字
a.innerHTML = hour
let minute = parseInt(date / 60 % 60)//分
minute = minute < 10 ? '0' + minute : minute //如果小于10就在前面加0,否则就是正常数字
b.innerHTML = minute
let second = parseInt(date % 60) //秒
second = second < 10 ? '0' + second : second //如果小于10就在前面加0,否则就是正常数字
c.innerHTML = second
当时间全部为0的时候会提示双十一快乐
setTimeout(function () {
if (day == 00 && hour == 00 && minute == 00 && second == 00) {
console.log('双十一快乐')
}
})
}
时间每隔一秒刷新一次