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>

 

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