HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>倒计时按钮</title>
<style>
/* 发送按钮禁止样式 */
.sentBtn.disabled {
background-color: #CCC !important;
cursor: not-allowed !important;
}
/* 发送按钮样式 */
.sentBtn{
min-width: 100px;
padding: 5px;
border: none;
color: #FFF;
background-color: #83EBF0;
border-radius: 4px;
cursor: pointer;
}
</style>
</head>
<body>
<input type="button" value="获取验证码" class="sentBtn">
</body>
</html>
<!-- 导入jQuery -->
<script src="js/jquery.min.js"></script>
<script>
var flag = true; //解决连续点击事件bug
$('.sentBtn').click(function () {
if(flag == true){
$(this).addClass("disabled"); //点击获取验证码后,禁用该按钮,开始倒计时
flag = false;
var time = 10; //倒计时时间,自定义
var $this = $(this); //备份,定时器是异步的,此this非彼this
var timer = setInterval(function () {
time--; //开始倒计时
if (time == 0) { //当倒计时为0秒时,关闭定时器,更改按钮显示文本并设置为可以点击
clearInterval(timer);
$this.val('获取验证码');
$this.removeClass("disabled");
flag = true;
return;
}
$this.val('还剩' + time + "秒"); //显示剩余秒数
}, 1000); //定时器一秒走一次,每次减一,就是倒计时了
}else{
return;
}
});
</script>
效果图: