发送验证码
需求
1、发送按钮点击后,会被禁用
2、被点击后,按钮里面的内容会变化成1分钟的倒计时;
3、待发送按钮被触发后才可以点击提交按钮,需在验证码框里填写0505,用弹窗提示成功。
实现原理
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
height: 200px;
display: flex;
align-items: center;
justify-content: center;
}
#input {
width: 200px;
height: 20px;
border: 1px solid #b0b0b0;
outline: none;
padding: 5px;
}
button {
border: 1px solid #b0b0b0;
height: 31px;
background-color: #364c7b;
color: #fff;
}
.submit {
border: 1px solid #b0b0b0;
height: 31px;
background-color: #fff;
outline: none;
}
</style>
</head>
<body>
<div>
<input type="password" id="input">
<button class="send">发送</button>
<input type="submit" class="submit">
</div>
<script>
const send = document.querySelector('button');
let time = 60; //初始化禁用时间
send.addEventListener('click', function () {
send.disabled = true;
const timer = setInterval(function () {
if (time == 0) {
//清除定时器
clearInterval(timer);
send.innerHTML = '发送';//定时完成恢复发送样式
} else {
send.innerHTML = '倒计时' + time + '秒';//倒计时不为零时设置文字样式
time--;
}
}, 100);//播放速度
const submit = document.querySelector('.submit')
const num = document.querySelector('#input')
submit.addEventListener('click', function () {
let pass = num.value //获取密码的值
//判断是否输入准确
if (pass == '0505') {
alert('提交成功😁')
} else {
alert('有内鬼,终止交易🤪')
}
})
});
</script>
</body>
</html>
效果展示
js点击获取短信验证码
场景:
在注册或者忘记密码等功能中写手机号码之后,通常会获取验证码这一操作。
步骤:
1.在按钮上添加点击事件;
2.在点击事件里先验证是否填写和合法的手机号;
3.在进行接口调取获取验证码;
4.使用定时器来判断按钮的变化;
vue实现:
//结构
<el-form-item label="短信验证码:" prop="phoneCode">
<el-input v-model="ruleForm.phoneCode" maxlength="4"></el-input>
<el-button type="primary" @click.prevent="getCode()" :disabled="isCodeDisabled">
{{ !isCodeDisabled ? '获取验证码' : (count + 's') }}
</el-button>
</el-form-item>
//获取短信验证码
getCode(){
this.$refs.ruleForm.validateField('registerPhone',(errorMsg) => {
if(!!errorMsg) return ;
if(!this.timer){
this.count = 60;
var params = {
phoneType:'RG',
phone:this.ruleForm.registerPhone
}
VerifyCodePhone(params).then(res => {
if(res.code == 200) {
this.ruleForm.uuid = res.data.verificationPhoneCodeUUID;
this.utils.success('短信验证码发送成功');
}
})
this.isCodeDisabled = true;
this.timer = setInterval(() => {
if(this.count > 0 && this.count <= 60){
this.count --;
}else {
this.isCodeDisabled = false;
clearInterval(this.timer);
this.timer = null;
}
},1000)
}
})
},