js獲取驗證碼倒計時(兩種方式,親測可用)

一.當標籤爲按鈕是,設置disabled屬性

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title></title>
		<script type="text/javascript">
			document.addEventListener('plusready', function() {
				//console.log("所有plus api都應該在此事件發生後調用,否則會出現plus is undefined。"

			});
		</script>
	</head>

	<body>
		<input id="btn" type="button" value="獲取驗證碼" />
		<!--
		<button id="btn" type="button" value="獲取驗證碼" style="width: 60px; height: 30px; line-height:30px;background-color: #3385FF;color: white;" ></button>
		-->
		<script type="text/javascript">
			var wait = 60;
			function time(o) {
				if(wait == 0) {
					o.removeAttribute("disabled");
					o.value = "獲取驗證碼";
					wait = 60;
				} else {
					o.setAttribute("disabled", true);
					o.value = "重新發送(" + wait + ")";
					wait--;
					setTimeout(function() {
						time(o);
					}, 1000)
				}
			}
			document.getElementById("btn").onclick = function() {
				time(this);
			}
		</script>
	</body>

</html>

二.標籤爲span時,無法添加disalbed屬性

<div class="H-flexbox-horizontal H-border-vertical-bottom-margin-both-10-after">
	<input type="tel" id="mobile" class="" placeholder="請輸入手機號" />
</div>
<div class="H-flexbox-horizontal  H-border-vertical-bottom-margin-both-10-after" id="getMessage">
	<input type="text" id="sms" class="" placeholder="短信驗證碼" /><span id="TencentCaptcha" onclick="TencentCaptcha(this)" class="">獲取驗證碼</span>
</div>

<script>
    function TencentCaptcha (e) {
		var mobile = $('#mobile').val();
		if(mobile==""){
			H.toastTip(null, '請先輸入手機號!', 2000, "middle");
			return;
		}
		var url='/user/singleSend/mobile/'+mobile;
			ajaxRequest(url, 'get', '', function(ret){
				if(ret.code==200){  //根據接口回調數據判斷驗證碼是否發送
					H.toastTip(null, ret.msg, 2000, "middle");
					settime(e)    //發送驗證碼成功,調用倒計時函數
				}else{
					H.toastTip(null, ret.msg, 2000, "middle");
				}
		    })
		}

	var time=60;
    function settime(e) {
		var val=$("#TencentCaptcha");
        if (time == 0) {
            val.addClass("H-theme-font-color1");
            val.removeClass("H-theme-font-color-ccc");
			e.setAttribute("onclick","TencentCaptcha(this)");
			val.html("重新發送驗證碼");
            time = 60;
        } else {
			val.removeClass("H-theme-font-color1");
			val.addClass("H-theme-font-color-ccc");
			e.removeAttribute("onclick");
			val.html("已發送(" + time + ")");
            time--;
            setTimeout(function() {
                settime(e)
            },1000)
        }
    }
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章