1.效果预览
2.实现思路
- 制作6个小的正方形div
- 用一个input覆盖在6个div上
- 给input设置透明(隐藏掉input)
3.源码
- html
<div class="input-box flexbox">
<div class="code-item" :class="codeValue.length == 0 && inputFocus ? 'code-item-active' : ''">{{codeValue[0]}}</div>
<div class="code-item" :class="codeValue.length == 1 && inputFocus ? 'code-item-active' : ''">{{codeValue[1]}}</div>
<div class="code-item" :class="codeValue.length == 2 && inputFocus ? 'code-item-active' : ''">{{codeValue[2]}}</div>
<div class="code-item" :class="codeValue.length == 3 && inputFocus ? 'code-item-active' : ''">{{codeValue[3]}}</div>
<div class="code-item" :class="codeValue.length == 4 && inputFocus ? 'code-item-active' : ''">{{codeValue[4]}}</div>
<div class="code-item" :class="codeValue.length >= 5 && inputFocus ? 'code-item-active' : ''">{{codeValue[5]}}</div>
<el-input class="input-code"
:value="codeValue"
:maxlength="6"
@blur="codeInputBlur"
@focus="codeInputFocus"
@input="codeInputChange">
</el-input>
</div>
- css
.input-box {
margin-top: 20px;
position: relative;
}
.input-code {
position: absolute;
}
.code-item {
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
border: 1px solid #f0f0f0;
margin-right: 10px;
}
.code-item-active {
border: 1px solid #F23026;
box-sizing: border-box;
}
// 隐藏input
.input-box {
.el-input__inner {
width: 362px;
height: 50px;
background-color: transparent;
border: none;
color: transparent;
}
}
- js
data() {
return {
codeValue: '',
inputFocus: false,
sendCodeFlag: false,
codeTime: 59,
};
},
methods: {
// 发送验证码
sendCode() {
this.codeTime = 59;
this.sendCodeFlag = true;
const timer = setInterval(() => {
this.codeTime -= 1;
if (this.codeTime <= 0) {
this.sendCodeFlag = false;
clearInterval(timer);
}
}, 1000);
},
// 验证码输入框
codeInputChange(e) {
if (e) {
// 判断输入内容是否为数字
if ((/^\+?[0-9][0-9]*$/).test(e)) {
this.codeValue = e;
}
} else {
this.codeValue = '';
}
},
// 验证码输入框失去焦点
codeInputBlur() {
this.inputFocus = false;
},
// 验证码输入框获取到焦点
codeInputFocus() {
this.inputFocus = true;
},
},