Js获取验证码倒计时
1.Jquery的实现:
/**
* 倒计时
* e 代表发送按钮对象
*/
function resetTime(e){
var second = 60;
var timer = null;
timer = setInterval(function(){
second -= 1;
if(second >0){
$(e).attr('disabled',true);
$(e).text(second + "秒后获取验证码");
}else{
clearInterval(timer);
$(e).attr('disabled',false);
$(e).text("发送短信验证码");
}
},1000);
}
https://www.houdianzi.com vi设计公司
2、在vue实现倒计时获取验证码效果:
这里我们没有使用setInterval,而使用setTimeout,每1秒钟递归来实现的。注意区别:
<template>
<div>
<el-button :disabled="disabled" @click="sendcode" class="sendcode">{{btntxt}}</el-button>
</div>
</template>
<script>
export default {
data() {
return {
disabled: false,
time: 5,
btntxt: "发送验证码",
};
},
methods: {
sendcode() {
this.time = 5;
this.timer();
},
//发送手机验证码倒计时
timer() {
if (this.time > 0) {
this.disabled = true;
this.time--;
this.btntxt = this.time + "秒";
setTimeout(this.timer, 1000);
} else {
this.time = 0;
this.btntxt = "发送验证码";
this.disabled = false;
}
},
}
}
</script>
<style scoped>
.el-button {
margin: 100px 50px;
}
</style>