<input type="text" name="retrieveCode" placeholder="请输入邮箱验证码"/>
<button id="retrieve-code" type="button" class="get-code get-code-hover email-retrieve-code">获取验证码</button>
// 点击事件调用倒计时函数
setTime($('#retrieve-code'), 60);
/**
* 点击按钮开始倒计时
* @param obj 倒计时操作的文档对象
* @param countdown 倒计时时间
*/
function setTime(obj, countdown) {
if (countdown == 0) {
obj.removeProp('disabled');
obj.addClass('get-code-hover');
obj.html("获取验证码");
return;
} else {
obj.prop('disabled', 'disabled');
obj.removeClass('get-code-hover');
obj.html("重新发送(" + countdown + ")");
countdown--;
}
setTimeout(function() {
setTime(obj, countdown);
}, 1000)
};
当点击获取验证码按钮时,调用setTime函数,其中第一个参数表示需要被操作的文档对象,第二个参数代表倒计时的时间,当开始倒计时一直到倒计时结束前这段时间,必须设置按钮为不可点击状态,倒计时结束后,将其恢复到可点击状态。