利用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>