JavaScript基础学习 页面显示倒计时效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=devcie-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
margin: 200px;
}
span {
display: inline-block;
width: 40px;
height: 40px;
background-color: #333;
font-size: 20px;
color: #fff;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div>
<span id="hours">1</span>
<span id="minutes">2</span>
<span id="seconds">3</span>
</div>
<script>
var hours = document.querySelector('#hours');
var minutes = document.querySelector('#minutes');
var seconds = document.querySelector('#seconds');
var nowTime = +new Date('2021-12-21 22:00:00');
console.log(nowTime);
// 开头就执行一次倒计时函数 为了在刷新时不显示页面空白而直接显示剩余时间
getTimers();
setInterval(getTimers, 1000);
function getTimers() {
var date = +new Date();
var timeOut = (nowTime - date) / 1000;
h = parseInt(timeOut / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
m = parseInt(timeOut / 60 % 60);
m = m < 10 ? '0' + m : m;
s = parseInt(timeOut % 60);
s = s < 10 ? '0' + s : s;
hours.innerHTML = h;
minutes.innerHTML = m;
seconds.innerHTML = s;
}
</script>
</body>
</html>
