前言
在手机端输入短信验证码时,经常会遇到有需求要弄一个好看点的验证样式,下面简单分享一下自己写的一个例子
<view class="sms_wrap">
<input class="ipt" :focus="autoFocus" type="number" @input="handleInput" />
<view class="ipt_box" :style="iptBoxStyle">
<block v-for="(item, index) in range" :key="index">
<view class="ipt_k" :class=" codeArr.length > index ? 'active' : '' ">
<text class="txt">{{codeArr[index]}}</text>
</view>
</block>
</view>
</view>
<script>
export default {
data () {
return {
iptBoxStyle: 'width: 700rpx;left: 25rpx;',
range: [],
codeArr: [],
nextCodeIndex: 1,
}
},
props: {
maxlength: {
type: Number,
default: 6
},
autoFocus: {
type: Boolean,
default: false
}
},
computed: {
},
mounted() {
if(this.maxlength === 6){
this.range = [1,2,3,4,5,6]
this.iptBoxStyle = 'width: 700rpx;left: 25rpx;'
}else if(this.maxlength === 4){
this.range = [1,2,3,4]
this.iptBoxStyle = 'width: 460rpx;left: 145rpx;'
}
},
methods: {
handleInput(event) {
let val = event.detail.value
if(val.length <= this.maxlength){
this.nextCodeIndex = val.length + 1
let arr = val.split('')
this.codeArr = arr
if(this.nextCodeIndex > this.maxlength) {
uni.hideKeyboard()
setTimeout(()=>{
this.$emit('finish', this.codeArr.join(''))
},500)
}
}
}
},
}
</script>
<style scoped>
.sms_wrap{
position: relative;
width: 750rpx;
}
.sms_wrap .ipt{
position: absolute;
top: 0;
left: -100%;
width: 200%;
opacity: 0;
height: 100rpx;
z-index: 10;
}
.ipt_box{
position: absolute;
top: 0;
display: flex;
justify-content: space-between;
height: 100rpx;
}
.ipt_k{
display: flex;
align-items: center;
justify-content: center;
width: 100rpx;
height: 100rpx;
border: 1rpx solid #C0C0C0;
box-sizing: border-box;
}
.ipt_k.active{
border-color: #00C777;
}
.ipt_k .txt{
font-size: 40rpx;
color: #333333;
}
</style>