利用js实现的短信验证码倒计时按钮

利用js实现的短信验证码倒计时按钮

最近在做一个登陆页面,需要一个发送验证码的倒计时按钮,在网上找了好多例子,结果都不尽人意,于是自己写了一个简单的样例,放在这里记录一下。
点击后开始倒计时,计时结束后显示“重新发送”
先是按钮点击前后的两个样式:

			.btnCode {
				width: 100px;
				height: 42px;
				background: #FFF;
				color: #323333;
				font-size: 14px;
			}
			.btnCodeDisabled {
				width: 100px;
				height: 42px;
				background: #ccc;
				color: #323333;
				font-size: 14px;
			}

然后再把按钮写上去

<input type="button" id="getCode" value="获取验证码" class="btnCode" />

最后是JS样式,通过事件绑定函数和setTimeout定时器来实现倒计时功能:

		$(function() {
			var wait = 60;

			function time(obj) {
				if (wait == 0) {
					obj.className = 'btnCode';
					obj.removeAttribute("disabled");
					obj.value = "重新获取";
					wait = 60;
				} else {
					obj.className = 'btnCodeDisabled'; //按钮变灰,不可点击
					obj.setAttribute("disabled", true);
					obj.value = "重新发送(" + wait + ")";
					wait--;
					setTimeout(function() {
							time(obj)
						},
						1000)
				}
			}
			document.getElementById("getCode").onclick = function() {
				time(this);
			}
		})

下面是完整的代码:

<html>
	<head>
		<style type="text/css">
			.btnCode {
				width: 100px;
				height: 42px;
				background: #FFF;
				color: #323333;
				font-size: 14px;
			}

			.btnCodeDisabled {
				width: 100px;
				height: 42px;
				background: #ccc;
				color: #323333;
				font-size: 14px;
			}
		</style>
	<body>
		<input type="button" id="getCode" value="获取验证码" class="btnCode" />
	</body>
	<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
	<script type="text/javascript">
		$(function() {
			var wait = 60;

			function time(obj) {
				if (wait == 0) {
					obj.className = 'btnCode';
					obj.removeAttribute("disabled");
					obj.value = "重新获取";
					wait = 60;
				} else {
					obj.className = 'btnCodeDisabled'; //按钮变灰,不可点击
					obj.setAttribute("disabled", true);
					obj.value = "重新发送(" + wait + ")";
					wait--;
					setTimeout(function() {
							time(obj)
						},
						1000)
				}
			}
			document.getElementById("getCode").onclick = function() {
				time(this);
			}
		})
	</script>

</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值