今天测试提了一个bug,发送短信倒计时功能,要求关闭页面也要进行倒计时。这想到了,当年我参与的周杰伦演唱会的先付先抢功能。与之类似,只不过,那个项目的时间都是服务器时间,本人目前有点偷懒,就用客户端的时间了。
一下是完整的代码,只不过在客户端的效率不是很好。
<!doctype html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> <script src="http://cdn.bootcss.com/jquery/3.1.0/jquery.js"></script> <script src="http://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script> <!--<script src="jquery.min.js"></script>--> <!-- <script src="jquery.cookie.js"></script>--> <!-- <script src="//cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>--> </head> <body> <input id="memberTel" type="text" value="18518181818"/> <input id="code_btn" type="button" value="免费获取验证码" /> </body><script>
$(function(){ checkCountdown(); $("#code_btn").click(function (){ if(count_down > 0){ return; } sendCode($("#code_btn")); });})//校验打开页面的时候是否要继续倒计时function checkCountdown(){ var secondsremained = $.cookie("secondsremained"); if(secondsremained){ var date = new Date(unescape(secondsremained)); setCoutDown(date,$("#code_btn")); }}//发送验证码function sendCode(obj){ var result = isPhoneNum(); if(result){ //加载ajax 获取验证码的方法 getCaptcha(); var date = new Date(); addCookie("secondsremained",date.toGMTString(),60);//添加cookie记录,有效时间60s setCoutDown(date,obj); }}var nowDate = null;var time_difference = 0;var count_down = 0;function setCoutDown(date,obj) { nowDate = new Date(); time_difference = ((nowDate- date)/1000).toFixed(0); count_down = 60 - time_difference; console.log(count_down); if(count_down<=0){ obj.removeAttr("disabled"); obj.removeClass("code_grey"); obj.html("获取验证码"); obj.val("获取验证码"); addCookie("secondsremained","",60);//添加cookie记录,有效时间60s return; } obj.attr("disabled", true); obj.addClass("code_grey"); obj.html(count_down + "秒后重发"); obj.val(count_down + "秒后重发"); setTimeout(function() { setCoutDown(date,obj) },1000) //每1000毫秒执行一次}//发送验证码时添加cookiefunction addCookie(name,value,expiresHours){ //判断是否设置过期时间,0代表关闭浏览器时失效 if(expiresHours>0){ var date=new Date(); date.setTime(date.getTime()+expiresHours*1000); $.cookie(name, escape(value), {expires: date}); }else{ $.cookie(name, escape(value)); }}//校验手机号是否合法function isPhoneNum(){ var mobile = $("#memberTel").val(); if($.trim(mobile) =="" || !(/^1[3|4|5|7|8]\d{9}$/.test(mobile))){ tooltip().show('提示','请输入正确手机号码'); return false; } return true;}function getCaptcha(){ $.ajax({ type: 'GET', url: basePath + '/getcaptcha', data: { "mobile":mobile }, async: false, dataType: "json", });}</script> </html>