基于jQuery实现发送短信验证码后的倒计时功能(无视页面关闭)
相关阅读:
基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)
今天测试提了一个bug,发送短信倒计时功能,要求关闭页面也要进行倒计时。这想到了,当年我参与的周杰伦演唱会的先付先抢功能。与之类似,只不过,那个项目的时间都是服务器时间,本人目前有点偷懒,就用客户端的时间了。
一下是完整的代码,只不过在客户端的效率不是很好。
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="Generator"content="EditPlus®">
<metaname="Author"content="">
<metaname="Keywords"content="">
<metaname="Description"content="">
<title>Document</title>
<scriptsrc="http://cdn.bootcss.com/jquery/3.1.0/jquery.js"></script>
<scriptsrc="http://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<!--<scriptsrc="jquery.min.js"></script>-->
<!--<scriptsrc="jquery.cookie.js"></script>-->
<!--<scriptsrc="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>-->
</head>
<body>
<inputid="phonenum"type="text"value="18518181818"/>
<inputid="second"type="button"value="免费获取验证码"/>
</body>
<script>
$(function(){
$("#second").click(function(){
sendCode($("#second"));
});
checkCountdown();
})
//校验打开页面的时候是否要继续倒计时
functioncheckCountdown(){
varsecondsremained=$.cookie("secondsremained");
if(secondsremained){
vardate=newDate(unescape(secondsremained));
setCoutDown(date,$("#second"));
}
}
//发送验证码
functionsendCode(obj){
varphonenum=$("#phonenum").val();
varresult=isPhoneNum();
if(result){
//加载ajax获取验证码的方法
//doPostBack('${base}/login/getCode.htm',backFunc1,{"phonenum":phonenum});
vardate=newDate();
addCookie("secondsremained",date.toGMTString(),60);//添加cookie记录,有效时间60s
setCoutDown(date,obj);
}
}
varnowDate=null;
vartime_difference=0;
varcount_down=0;
functionsetCoutDown(date,obj){
nowDate=newDate();
time_difference=((nowDate-date)/1000).toFixed(0);
count_down=60-time_difference;
console.log(count_down);
if(count_down<=0){
obj.removeAttr("disabled");
obj.val("免费获取验证码");
addCookie("secondsremained","",60);//添加cookie记录,有效时间60s
return;
}
obj.attr("disabled",true);
obj.val("重新发送("+count_down+")");
setTimeout(function(){setCoutDown(date,obj)},1000)//每1000毫秒执行一次
}
//发送验证码时添加cookie
functionaddCookie(name,value,expiresHours){
//判断是否设置过期时间,0代表关闭浏览器时失效
if(expiresHours>0){
vardate=newDate();
date.setTime(date.getTime()+expiresHours*1000);
$.cookie(name,escape(value),{expires:date});
}else{
$.cookie(name,escape(value));
}
}
//校验手机号是否合法
functionisPhoneNum(){
varphonenum=$("#phonenum").val();
varmyreg=/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if(!myreg.test(phonenum)){
alert('请输入有效的手机号码!');
returnfalse;
}else{
returntrue;
}
}
</script>
</html>
以上所述是小编给大家介绍的基于jQuery实现发送短信验证码后的倒计时功能(无视页面关闭),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!