?要实现以上自动更新时间的倒计时效果,要使用的知识点有Date对象,Math对象,setInterval函数
<style>
div {
margin: 100px auto;
width: 500px;
height: 100px;
line-height: 100px;
font-size: 20px;
text-align: center;
border: 1px solid #ccc;
box-shadow: 5px 5px 2px #7a7171;
}
#time {
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<div>
距离2022-1-1倒计时:
<span id="time">xxx天-xxx时-xxx分-xxx秒!</span>
</div>
</body>
<script>
// 需求:在页面中显示距离距离2022-1-1的倒计时
let time = document.querySelector('#time') //获取元素
function countdown() {
let curDate = new Date() //获取当前日期
let assignDate = new Date('2022-1-1 00:00:00') //设置未来日期
let diff = assignDate - curDate; //时间差
let day = Math.floor(diff / 1000 / 60 / 60 / 24) //计算天
let hour = Math.floor(diff / 1000 / 60 / 60 % 60) //计算小时
let minute = Math.floor(diff / 1000 / 60 % 60) //计算分
let second = Math.floor(diff / 1000 % 60) //计算秒
time.textContent = `${day}天-${hour}时-${minute}分-${second}秒!` //渲染在页面中
}
countdown(); //立即执行
setInterval(countdown, 1000) //设置循环间隔,每1000毫秒调用一次函数
</script>
|