<!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;
/* background-size: 240px; */
/* float: left; */
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">今天是2222年2月22日</p>
<p class="title">下课倒计时</p>
<p class="clock">
<span id="hour">00</span>
<i>:</i>
<span id="minutes">25</span>
<i>:</i>
<span id="second">20</span>
</p>
<p class="tips">18:30:00下课</p>
</div>
<script>
function getCountTime() {
//年月日
const date = new Date()
let y = date.getFullYear()
let M = (date.getMonth() + 1)
let d = date.getDate()
console.log(y, M, d)
//得到未来的某一个时间的时间戳
const fTime = +new Date('2022-7-26 12:00:00')
console.log(fTime)
//得到现在的时间的时间戳
const nTime = +new Date()
console.log(nTime)
//用将来的-现在的时间戳
const time = (fTime - nTime) / 1000
console.log(time)
//将时间戳转化为时分秒
h = parseInt(time / 60 / 60 % 24)
h = h < 10 ? '0' + h : h
m = parseInt(time / 60 % 60)
m = m < 10 ? '0' + m : m
s = parseInt(time % 60)
s = s < 10 ? '0' + s : s
console.log(h, m, s)
//将年月日整合放入相应的盒子中
const res = `今天是${y}年-${M}月-${d}日`
document.querySelector('.next').innerHTML = res
//将倒计时整合放入相应盒子中
document.querySelector('#hour').innerHTML = h
document.querySelector('#minutes').innerHTML = m
document.querySelector('#second').innerHTML = s
}
getCountTime()
//加入定时器 让其自动倒计时
setInterval(getCountTime, 1000)
</script>
</body>
</html>
javascript倒计时案例(时间戳)
最新推荐文章于 2024-08-19 15:50:15 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)