实现点击验证码开始倒计时
在项目中涉及到短信验证功能时必不可少的是发送验证码的点击后倒计时效果,本次记录使用jquery和vue两种方式的实现:
使用jquery实现
- HTML部分
<form>
<input type="number" class="iphone" name="iphone" maxlength="11" placeholder="请输入11位手机号" id="codeMobile" />
<input type="number" class="code" name="code" maxlength="4" placeholder="请输入4位验证码" id="code" />
<input type="button" id="btnSend" class="btn-code" value="发送验证码" disabled="disabled" />
<input type="button" class="submit" value="登录" id="subloginCode" />
</form>
- js部分
//封装倒计时函数
var wait = 60;
function time(o) {
if(wait == 0) {
$(o).removeAttr("disabled").val("重新获取").css({
'background': '#d0e8d2',
'color': '#8aa78a',
'box-shadow': '0 0px 3px 0px #a5d4ad'
});
wait = 60;
} else {
$(o).attr("disabled", 'disabled').val('剩余' + wait + 's').css({
'background': '#eee',
'color': '#888',
'box-shadow': '0 0 0 0 #fff'
});
wait--;
setTimeout(function() {
time(o);
}, 1000);
}
}
//点击发送验证码按钮
var btnSend = $('#btnSend');
btnSend.on('click', function() {
...
//如果不嵌套发送验证的ajax可直接使用time(this)
time(btnSend)
...
})
使用vue实现
- HTM部分
<input type="button" id="btnSend" class="btn-code" value="发送验证码" disabled="disabled" v-model='btnSend' @click="sendCode" ref="btnSend" />
- js部分(在methods中定义sendcode方法)
//data中定义timer,count
count: '', //按钮上显示的秒值
timer: null
//methods中定义发送验证码方法
sendCode() {
...
this.pupUp('发送成功')
const num = 60
if (!this.timer) {
this.count = num
this.btnSend = '剩余' + this.count + '秒'
this.timer = setInterval(() => {
if (this.count > 0 && this.count <= num) {
this.count--
this.btnSend = '剩余' + this.count + '秒'
} else {
this.btnSend = '发送验证码'
clearInterval(this.timer)
this.timer = null
}
}, 1000)
}
},
记录点滴,每天进步一点点