最近在做登录验证的时候,感觉单纯的让用户输入一串数据有点Low,突然又想起来马爸爸的支付宝在付款输密码用的验证框非常有意思,于是就稍做借鉴和修改了一版出来,下面放代码。
1. 页面布局 (包一层主要是为了解决IOS光标移位的问题)
<view class="check">
<input class="checkInput" ref="check1" type="number" focus maxlength="1" @input="checkInput(1)" />
</view>
<view class="check">
<input class="checkInput" ref="check2" type="number" maxlength="1" @input="checkInput(2)" />
</view>
<view class="check">
<input class="checkInput" ref="check3" type="number" maxlength="1" @input="checkInput(3)" />
</view>
<view class="check">
<input class="checkInput" ref="check4" type="number" maxlength="1" @input="checkInput(4)" />
</view>
<view class="check">
<input class="checkInput" ref="check5" type="number" maxlength="1" @input="checkInput(5)" />
</view>
<view class="check">
<input class="checkInput" ref="check6" type="number" maxlength="1" @input="checkInput(6)" />
</view>
2.CSS
.check {
height: 103upx;
width: 15%;
margin-left: 2upx;
border: 1px solid white;
display: inline-block;
color: white;
}
.checkInput {
padding: 32upx;
z-index: 999;
font-size: 0.75rem;
}
3.JS方法实现
checkInput(index) {
var nextIndex = 1;
//获取当前输入值
let value = this.$refs["check" + index].inputValue;
if (value.trim() === "") {
nextIndex = index === 1 ? 1 : index - 1;
} else {
nextIndex = index + 1;
}
//nextIndex取值区间为1~7
//1~6可以视为验证码的更改,7为自动提交
if (nextIndex === 7) {
this.checkLogin()
} else {
this.$refs["check" + nextIndex].$refs.input.focus()
}
},
缺点:在未输入任何数据时,中途退格会失效(可以考虑将focus改成select,如果大家有更好的方案,可以一起交流。)