js实现一个页面多个倒计时的3种方法
程序员文章站
2022-11-25 22:46:42
本文实例为大家分享了js实现一个页面多个倒计时的具体代码,供大家参考,具体内容如下
说明: 方法1, 方法二是基础原理版,方法三升级版(参考for循环,定时器,闭包混合一...
本文实例为大家分享了js实现一个页面多个倒计时的具体代码,供大家参考,具体内容如下
说明: 方法1, 方法二是基础原理版,方法三升级版(参考for循环,定时器,闭包混合一块的那点事。)
方法一:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>倒计时</title> </head> <body> <div id="timer1" style="color:red"></div> <div id="timer2" style="color:red"></div> </body> <script> function countdown( maxtime,fn ) { var timer = setinterval(function() { if( !!maxtime ){ var day = math.floor(maxtime / 86400), hour = math.floor((maxtime % 86400) / 3600), minutes = math.floor((maxtime % 3600) / 60), seconds = math.floor(maxtime%60), msg = "距离结束还有"+day+"天"+hour+"时"+minutes+"分"+seconds+"秒"; fn( msg ); --maxtime; } else { clearinterval( timer ); fn("时间到,结束!"); } }, 1000); } countdown( 86,function( msg ) { document.getelementbyid('timer1').innerhtml = msg; }) countdown( 86400,function( msg ) { document.getelementbyid('timer2').innerhtml = msg; }) </script> </html>
方法二:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>倒计时</title> </head> <body> <div id="timer1"></div> <div id="timer2"></div> <div id="timer3"></div> </body> <script type="text/javascript"> var addtimer = function () { var list = [], interval; return function (id, time) { if (!interval) interval = setinterval(go, 1000); list.push({ ele: document.getelementbyid(id), time: time }); } function go() { for (var i = 0; i < list.length; i++) { list[i].ele.innerhtml = gettimerstring(list[i].time ? list[i].time -= 1 : 0); if (!list[i].time) list.splice(i--, 1); } } function gettimerstring(time) { var not0 = !!time, d = math.floor(time / 86400), h = math.floor((time %= 86400) / 3600), m = math.floor((time %= 3600) / 60), s = time % 60; if (not0) return "还有" + d + "天" + h + "小时" + m + "分" + s + "秒"; else return "时间到"; } } (); addtimer("timer1", 12); addtimer("timer2", 10); addtimer("timer3", 13); </script> </html>
方法三:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>倒计时</title> </head> <body> <div id="timer0" style="color:red"></div> <div id="timer1" style="color:red"></div> <div id="timer2" style="color:red"></div> </body> <script> function countdown( maxtime,fn ) { var timer = setinterval(function() { if( !!maxtime ){ var day = math.floor(maxtime / 86400), hour = math.floor((maxtime % 86400) / 3600), minutes = math.floor((maxtime % 3600) / 60), seconds = math.floor(maxtime%60), msg = "距离结束还有"+day+"天"+hour+"时"+minutes+"分"+seconds+"秒"; fn( msg ); --maxtime; } else { clearinterval( timer ); fn("时间到,结束!"); } }, 1000); } var atime = [3600,3800,3900]; for ( var i = 0; i < 3; i++ ) { (function (i) { var obj = 'timer' + i; countdown( atime[i],function( msg ) { document.getelementbyid(obj).innerhtml = msg; }) })(i) } </script> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 深入Node TCP模块的理解