原文地址:http://www.oschina.net/code/snippet_2001568_48311
特别说明:cookie最初创建的有效时间是60秒。也就是说,你如果在倒计时为20的时候,关闭网页.20秒之后再打开,是不会有倒计时显示的;但是,如果倒计时为20时,关闭页面,如果在20秒内重新打开页面,是有倒计时显示的。
CSS:
.inp_number{ width: 200px; height: 30px;}
.sendBtn{ width: 120px; height: 35px; background: #4b8ccb; border: none; color: #FFF; cursor: pointer;}
.gray{ background: #c5c5c5; }
HTML:
<div class="message_send">
<input type="text" class="inp_number"/>
<input type="button" value="发送验证码" class="sendBtn" id="send"/>
</div>
JS:
$(function(){
$('#send').click({function(){
sendCode($("#send"));
});
v = getCookieValue("secondsremained") ? getCookieValue("secondsremained") : 0; //获取cookie值
if(v>0){
settime($("#send"));//开始倒计时
}
}
//发送验证码
function sendCode(obj){
var phoneNum = $('.inp_number').val();
var resule = isPhoneNum();
if(result){
// doPostBack(url,backFunc1,{"phoneNum":phonenum});
addCookie("secondsremained",60,60); //添加cookie记录,有效时间为60s
settime(obj); //开始倒计时
}
}
//将手机利用ajax提交到后台的发短信接口
function doPostBack(url,backFunc,queryParam){
$.ajax({
async : false,
cache : false,
type : 'POST',
url : url, //请求的action路径
data : queryParam,
error : function(){
//请求失败处理函数
}
success : backFunc
});
}
function backFunc1(data){
var d = $.parseJSON(data);
if(!d.success){
alert(d.msg);
}else{
//返回验证码
alert("模拟验证码:" + d.msg);
$("#code").val(d.msg);
}
}
//发送验证码是添加cookie
function addCookie(name,value,expirseHours){
var cookieString = name + "=" + escape(value);
//判断是否设置过期时间,0代表关闭浏览器时失效
if(expiresHours > 0){
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
cookieString = cookieString + ";expires=" + date.toUTCString();
}
document.cookie = cookieString;
}
//修改cookie的值
function editCookie(name,value,expiresHours){
var cookieString = name + "=" + escape(value);
if(expiresHours > 0){
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
cookieString = cookieString + ";expires=" + date.toUTCString();
}
document.cookie = cookieString;
}
//根据名字获取cookie的值
function getCookieValue(name){
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
for(var i=0; i < arrCookie.length; i++){
var arr = arrCookie[i].split("=");
if(arr[0] == name){
return unescape(arr[1]);
break;
}
}
}
//倒计时
var countdown;
function settime(obj){
countdown = getCookieValue("secondsremained");
if(countdown == 0){
obj.removeAttr("disabled");
obj.val("免费获取验证码");
return;
}else{
obj.attr("disabled" , true);
obj.val("重新发送(" + countdown + ")" );
countdown--;
editCookie("secondsremained", countdown, countdown+1);
}
setTimeout(function(){
settime(obj)
},1000); //每1000秒执行一次
}
//验证手机号码是否合法
function isPhoneNum(){
var phoneNum = $('.inp_number').val();
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if(phoneNum == '' || !myreg.test(phoneNum)){
alert('请输入正确的手机号码!');
return false;
}else{
return false;
}
}