今天測試提了一個bug,發送短信倒計時功能,要求關閉頁面也要進行倒計時。這想到了,當年我參與的周杰倫演唱會的先付先搶功能。與之相似,只不過,那個項目的時間都是服務器時間,本人目前有點偷懶,就用客戶端的時間了。css
一下是完整的代碼,只不過在客戶端的效率不是很好。html
<!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>jquery
<script>ajax
$(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毫秒執行一次 } //發送驗證碼時添加cookie function 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>json