知识储备:
javascript Date对象
var now = new Date(); //获取当前时间
now.getFullYear(); //年份
now.getMonth(); //月份(0-11)
now.getDate(); //一个月中的某一天 (1 ~ 31)
now.getHours(); //时
now.getMinutes(); //分
now.getSeconds(); //秒
now.getTime(); //返回 1970 年 1 月 1 日至今的毫秒数。
场景:
1. 实现60s倒计时
<html>
<head>
<title>60秒倒计时</title>
</head>
<script type="text/javascript">
window.onload = function () {
var num = 60;
var time = document.getElementById("time");
var s = setInterval(function () {
num--;
time.innerText=num;
if(num<=0){
clearInterval(s)
}
},1000);
}
</script>
<body>
<div id="time">60</div>
</body>
</html>
2.距结束还有多久
<html lang="en">
<head>
<meta charset="UTF-8">
<title>倒计时2</title>
</head>
<script type="text/javascript">
window.onload = function () {
var time = document.getElementById("time");
var s = setInterval(function () {
var now = new Date();
var end = new Date("2017-06-05 19:45:00");
if(end>now){
var leftTime = end.getTime()-now.getTime();
var leftdays = Math.floor(leftTime/(1000*60*60*24));
var lefthours= Math.floor(leftTime/1000/60/60%24);
var leftminuins = Math.floor(leftTime/1000/60%60);
var leftSeconds = Math.floor(leftTime/1000%60);
var str =leftdays+"天"+ lefthours+"小时"+leftminuins+"分"+leftSeconds+"秒";
time.innerText=str;
if(leftdays==0&&lefthours==0&&leftminuins==0&&leftSeconds==0){
clearInterval(s);
}
}else{
time.innerText="已过了结束日期";
}
},1000);
}
</script>
<body>
<div id="time"></div>
</body>
</html>
3.倒计时5分钟
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5分钟倒计时</title>
</head>
<script type="text/javascript">
window.onload = function () {
var m = 5; //5分钟
var s = 60;//60s
var time = document.getElementById("time");
var sl = setInterval(function () {
if(s>0) {
s--;
}else{
m--;
s = 59;
}
var str = m+"分"+s+"秒";
time.innerText=str;
console.log(m+"分"+s+"秒")
if(m==0&&s==0){
clearInterval(sl);
}
},1000);
}
</script>
<body>
<div id="time"></div>
</body>
</html>
以上几个倒计时的场景,自己做了个总结。有不妥的地方,欢迎指正。谢谢~