JavaScript实现限时秒杀功能
时间:2022-03-23 10:01:35|栏目:JavaScript代码|点击: 次
本文实例为大家分享了JavaScript实现限时秒杀功能的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div class="box"> <div id="d"></div> <!-- 剩余的天数 --> <div id="h"></div> <!-- 剩余的小时 --> <div id="m"></div> <!-- 剩余的分钟 --> <div id="s"></div> <!-- 剩余的秒数 --> </div> <script> //设置秒杀结束时间 var endTime = new Date('2021-10-22 18:51:59'),endSeconds = endTime.getTime(); //定义变量保存剩余的时间 var d = h = m = s = 0; //设置定时器,实现限时秒杀效果 var id = setInterval(seckill,1000); function seckill(){ var nowTime = new Date(); //获取当前时间 //获取时间差,单位为秒 var remaining = parseInt((endSeconds - nowTime.getTime())/1000); if(remaining>0){//判断秒杀是否过期 //计算剩余天数(除以60*60*24取整,获取剩余的天数) d=parseInt(remaining / 86400); //计算剩余小时(除以60*60转换为小时,与24小时取模,获取剩余的小时) h=parseInt((remaining / 3600) % 24); //计算剩余分钟(除以60转为分钟,与60取模,获取剩余的分钟) m=parseInt((remaining / 60) % 60); //计算剩余秒(与60取模,获取剩余的秒数) s=parseInt(remaining % 60); //统一利用两位数表示剩余的天、小时、分钟、秒 d = d<10 ? '0' + d : d; h = h<10 ? '0' + h : h; m = m<10 ? '0' + m : m; s = s<10 ? '0' + s : s; }else{ clearInterval(id);//秒杀过期,取消定时器 d = h = m = s ='00'; } //将剩余的天,小时,分钟和秒显示到指定的网页中 document.getElementById('d').innerHTML = d + '天'; document.getElementById('h').innerHTML = h + '时'; document.getElementById('m').innerHTML = m + '分'; document.getElementById('s').innerHTML = s + '秒'; } </script> </body> </html>
再为大家分享一个JS实现简单的限时秒杀案例:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> .product{ border: 3px solid orange; display: inline-block; margin-left: 400px; width: 400px; } .red{ color: red; font-size: 25px; } </style> </head> <body> <div class="product" style="text-align: center;"> <img src="jquery案例-百叶窗/images/0.jpg" alt="" width="150"/> <p>绝世好男人</p> <span>原价:<del>99亿</del></span> <br/> <span>现价:<span class="red">100块</span></span> <br/> <span>距离抢购结束还有:</span><span id="time"></span> </div> <script> var stopTime = new Date(3000,11,14,0,0,0); var nowTime = new Date(); var jianGe = (stopTime-nowTime)/1000; var day = Math.floor(jianGe/60/60/24); var hour = Math.floor(jianGe/60/60%24); var min = Math.floor(jianGe/60%60); var sec = Math.floor(jianGe%60); var showTime = day+'天'+hour+'小时'+min+'分钟'+sec+'秒'; document.getElementById('time').innerText = showTime; //定时器:每隔多长事件执行一次某函数 //setInterval(func,ms) var timer = setInterval(function () { var nowTime = new Date(); var jianGe = (stopTime-nowTime)/1000; var day = Math.floor(jianGe/60/60/24); var hour = Math.floor(jianGe/60/60%24); var min = Math.floor(jianGe/60%60); var sec = Math.floor(jianGe%60); var showTime = day+'天'+hour+'小时'+min+'分钟'+sec+'秒'; document.getElementById('time').innerText = showTime; if(day==0&&hour==0&&min==0&&sec==0){ //关闭定时器 clearInterval(timer); } },1000); </script> </body> </html>
上一篇:JS对象深度克隆实例分析
栏 目:JavaScript代码
本文标题:JavaScript实现限时秒杀功能
本文地址:http://www.codeinn.net/misctech/197062.html