今天,我利用JavaScript制作了一个“开学倒计时”页面,大家可以依葫芦画瓢制作“新年倒计时”等等。希望我们互相学习,共同进步!
大家先来看看最终效果图:
HTML部分代码:
<html ang="en">
<head>
<meta charset="utf-8" />
<title>10.开学倒计时</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
font-family: "华文行楷";
font-size: 20px;
}
.time {
overflow: hidden;
margin: 100px auto;
border: 1px solid rgb(248, 248, 250);
text-align: center;
background: #f3eded;
border-radius: 10px;
padding: 20px;
width: 530px;
}
.time h3 {
font-size: 30px;
text-align: center;
padding-bottom: 30px;
letter-spacing: 5px;
}
.time h3 input {
border: none;
width: 100px;
height: 35px;
text-align: center;
border-radius: 8px;
background: #f2f2f2;
}
.time .even,
.time .odd {
float: left;
height: 50px;
text-align: center;
line-height: 50px;
margin-right: 10px;
border-radius: 8px;
}
.time .even {
width: 35px;
padding: 0 20px;
background: #ee4444;
color: #ffffff;
}
.time .odd {
width: 20px;
padding: 0 10px;
background: #ffffff;
}
#lastDiv {
margin-right: 0;
}
</style>
</head>
<body>
<div class="time">
<h3>距离2021年3月5日开学还剩下:</h3>
<div id="residueDays" class="even"></div>
<div class="odd">天</div>
<div id="residueHours" class="even"></div>
<div class="odd">时</div>
<div id="residueMinutes" class="even"></div>
<div class="odd">分</div>
<div id="residueSeconds" class="even"></div>
<div class="odd" id="lastDiv">秒</div>
</div>
</body>
</html>
js部分代码:
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function countDownTime() {
// 倒计时截止时间
var EndTime = new Date('2021/03/05 00:00:00');
// 现在的事件
var NowTime = new Date();
// 时间差(时间单位:ms)
var t = EndTime.getTime() - NowTime.getTime();
var d = 0;
var h = 0;
var m = 0;
var s = 0;
if(t >= 0) {
// 向下取整
d = Math.floor(t / 1000 / 60 / 60 / 24);
h = Math.floor(t / 1000 / 60 / 60 % 24);
m = Math.floor(t / 1000 / 60 % 60);
s = Math.floor(t / 1000 % 60);
}
// 如果是一位数,前面拼接"0"
function toDouble(num) {
return num < 10 ? '0' + num : num;
}
$("#residueDays").html(d);
$("#residueHours").html(toDouble(h));
$("#residueMinutes").html(toDouble(m));
$("#residueSeconds").html(toDouble(s));
}
setInterval(countDownTime, 1000)
</script>
小结:
1.倒计时算法思想是用预定时间—当前时间(当前时间用getTime()获取)。
2.HTML和JavaScript代码最好分成两个文件,比较清晰;如果大家嫌麻烦,当然也可以放在一起。