网络编程 发布日期:2024/11/16 浏览次数:1
本文实例为大家分享了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 "还有" + 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>
更多关于倒计时的文章请查看专题:《倒计时功能》
更多JavaScript时钟特效点击查看:JavaScript时钟特效专题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。