做项目时遇见了一个需求是邮箱验证码登录,并且自动聚焦到下一位,删除的时候也会自动聚焦到上一位,如图:
image.png
这边使用的是quasar 框架,看了网上很多的验证码方法都是使用的keydown,keyup方法来触发事件,但是在移动端不起作用,所以这边使用了input方法
<div class="input-main"><div v-for="(item,index) in securityCodeList" :key="index" >
<q-input oninput="this.value=this.value.replace(/\D/g,'');"
pattern="[0-9]*" outlined v-model="item.val" maxlength="1" :id="index" class="border-input" @input="nextFocus($event,index)"></q-input>
</div>
js代码
nextFocus(el,index) {
var dom = document.getElementsByClassName("border-input"),
currInput = dom[index],
nextInput = dom[index + 1],
lastInput = dom[index - 1];
if (el.keyCode != 8) {
if (index < (this.securityCodeList.length - 1) && el != "") {
nextInput.focus();
} else {
currInput.blur();
if(index != 0 ){
if(el == ""){
this.securityCodeList[index].val = "";
lastInput.focus();
}
}
}
}else{
if (index !=0) {
lastInput.focus();
}
}
let code = ""
this.securityCodeList.forEach(item =>{
code += item.val
})
if(code.length === 4){
const params = {
captcha: code
}
setEmailNumber(params).then(res =>{
// console.log(res)
if(res.code === "200"){
const sessionKey = res.data;
// this.getToken(sessionKey);
localStorage.setItem("token", sessionKey);
this.getInfo();
}
}).catch(error=>{
if(error.response.data.msg === "wrong captcha!"){
this.showTipText = true
}
})
}
},
如果需要有倒计时和再次触发的需求,可以参考下方代码
submitEmail() {
this.$refs.email.validate().then(async success => {
if (success) {
const sendRes = await sendEmailReq({
email: this.email.trim(),
expire: true
});
if (sendRes.code === "200") {
this.TimeValue =120
this.clock = window.setInterval(() => {
this.TimeValue -= 1;
this.openMagic();
this.TimeValue
if (this.TimeValue === 0) {
window.clearInterval(this.clock)
this.sendStatus = false
}
},1000)
}
}
});
},