本帖最后由 Amy 于 2019-1-5 10:55 编辑
【前端丨学习笔记】js实现倒计时功能
第一种:简单时长倒计时
比如一节课的时长倒计时
[HTML] 纯文本查看 复制代码 <html>
<head>
<meta charset="UTF-8">
<title>简单时长倒计时</title>
<SCRIPT type="text/javascript">
var maxtime = 45 * 60; //45分钟,按秒计算,60代表秒,可以自己调整!
function CountDown() {
if (maxtime >= 0) {
minutes = Math.floor(maxtime / 60);
seconds = Math.floor(maxtime % 60);
msg = "距离下课结束还有" + minutes + "分" + seconds + "秒";
document.all["timer"].innerHTML = msg;
if (maxtime == 5 * 60)alert("还剩5分钟");
--maxtime;
} else{
clearInterval(timer);
alert("时间到,结束!");
}
}
timer = setInterval("CountDown()", 1000);
</SCRIPT>
</head>
<body>
<div id="timer" style="color:red"></div>
<div id="warring" style="color:red"></div>
</body>
</html>
运行后效果:
运行到最后五分钟和结束时都会有弹窗提醒。
第二种:时分秒倒计时1
[HTML] 纯文本查看 复制代码 <head>
<meta charset="UTF-8">
<title>js简单时分秒倒计时</title>
<script type="text/javascript">
function countTime() {
//获取当前时间
var date = new Date();
var now = date.getTime();
//设置截止时间
var str="2019/5/20 00:00:00";
var endDate = new Date(str);
var end = endDate.getTime();
//时间差
var leftTime = end-now;
//定义变量 d,h,m,s保存倒计时的时间
var d,h,m,s;
if (leftTime>=0) {
d = Math.floor(leftTime/1000/60/60/24);
h = Math.floor(leftTime/1000/60/60%24);
m = Math.floor(leftTime/1000/60%60);
s = Math.floor(leftTime/1000%60);
}
//将倒计时赋值到div中
document.getElementById("_d").innerHTML = d+"天";
document.getElementById("_h").innerHTML = h+"时";
document.getElementById("_m").innerHTML = m+"分";
document.getElementById("_s").innerHTML = s+"秒";
//递归每秒调用countTime方法,显示动态时间效果
setTimeout(countTime,1000);
}
</script>
</head >
<body >
<div>
<span id="_d">00</span>
<span id="_h">00</span>
<span id="_m">00</span>
<span id="_s">00</span>
</div>
</body>
</html>
运行后效果:
第三种:时分秒倒计时2
[HTML] 纯文本查看 复制代码 <html>
<head>
<meta charset="UTF-8">
<title>JS实现倒计时(时、分,秒)</title>
<script language="javascript" type="text/javascript">
var interval = 1000;
function ShowCountDown(year, month, day, divname) {
var now = new Date();
var endDate = new Date(year, month - 1, day);
var leftTime = endDate.getTime() - now.getTime();
var leftsecond = parseInt(leftTime / 1000);
//var day1=parseInt(leftsecond/(24*60*60*6));
var day1 = Math.floor(leftsecond / (60 * 60 * 24));
var hour = Math.floor((leftsecond - day1 * 24 * 60 * 60) / 3600);
var minute = Math.floor((leftsecond - day1 * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftsecond - day1 * 24 * 60 * 60 - hour * 3600 - minute * 60);
var cc = document.getElementById(divname);
cc.innerHTML = "距离" + year + "年" + month + "月" + day + "日还有:" + day1 + "天" + hour + "小时" + minute + "分" + second + "秒";
}
window.setInterval(function () { ShowCountDown('2019', '05', '20', 'divdown1'); }, interval);
</script>
</head>
<body>
<div id="divdown1"></div>
</body>
</html>
运行后效果:
|