1.运行效果如下:
2.涉及到知识点有:
Date对象方法、Math对象方法
ES6知识包括:块作用域、解构赋值、模板字符串、箭头函数
3.代码如下(可以自行新建一个html文件粘贴代码后运行试试看):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style>
*{margin:0;padding:0;}
div{
font-size:30px;
}
span{
color:purple;
}
</style>
</head>
<body>
<div>距离2021年的六一儿童节还有:<span id="time1"></span></div>
<div>距离2021年的六一儿童节还有:<span id="time2"></span></div>
<div>距离2021年的六一儿童节还有:<span id="time3"></span></div>
<div>距离2021年的六一儿童节还有:<span id="time4"></span></div>
<script>
const time1 = document.getElementById("time1")
const time2 = document.getElementById("time2")
const time3 = document.getElementById("time3")
const time4 = document.getElementById("time4")
const {floor} = Math
let addZero = n => n < 10 ? "0" + n : n + "";
//
const aimDate = new Date("2021/6/1") //确定目标时间
const fn = () => {
const date = aimDate - new Date()
// 天数
const D = floor(date/24/60/60/1000)
// 小时
const h = floor(date/60/60/1000)%24
// 分钟
const m = floor(date/60/1000)%60
// 秒钟
const s = floor(date/1000)%60
time1.innerText = `${D}天`
time2.innerText = `${D}天${addZero(h)}小时`
time3.innerText = `${D}天${addZero(h)}小时${addZero(m)}分钟`
time4.innerText = `${D}天${addZero(h)}小时${addZero(m)}分钟${addZero(s)}秒`
}
setInterval(fn, 1000)
</script>
</body>
</html>
4.这里可以自行拓展成其他的倒计时,比如:
(1)下一次双十一时间
(2)下一次春节
(3)下一次母亲节
…