代码如下:
<template>
<div style="margin-top:50px">
<div class="phone">
<span>155</span>
<span class="input">
<input class="write" type="text" maxlength="1" v-model="input1" @keydown="inputKey(0)" />
<input class="write" type="text" maxlength="1" v-model="input2" @keydown="inputKey(1)" />
<input class="write" type="text" maxlength="1" v-model="input3" @keydown="inputKey(2)" />
<input class="write" type="text" maxlength="1" v-model="input4" @keydown="inputKey(3)" />
</span>
<span>0529</span>
</div>
</div>
</template>
<script>
export default {
watch: {
// 监听input 的输入,进而获去焦点
input1(val) {
let input = document.querySelectorAll(".write");
if (val) {
input[1].focus();
}
},
input2(val) {
let input = document.querySelectorAll(".write");
if (val) {
input[2].focus();
}
},
input3(val) {
let input = document.querySelectorAll(".write");
if (val) {
input[3].focus();
}
}
},
data() {
return {
input1: null,
input2: null,
input3: null,
input4: null,
};
},
methods: {
inputKey(index) {
let input = document.querySelectorAll(".write");
//当清除input数值时
if (event.keyCode == 8 && !input[index].value) {
if (input[index - 1]) {
input[index - 1].focus();
}
}
}
}
};
</script>
<style lang="scss" scoped>
.phone {
width: 100%;
text-align: center;
span {
font-size: 17px;
letter-spacing: 0.5rem;
margin: 0 5px;
}
.input {
input:last-child {
border: 1px solid #f1f1f1;
}
input {
display: inline-block;
width: 40px;
height: 40px;
border: 1px solid #f1f1f1;
border-radius: 0;
user-select: none;
outline: none;
border-right: none;
text-align: center;
font-weight: bold;
font-size: 17px;
transition: transform 0.3s, box-shadow 0.3s;
position: relative;
&:focus {
transform: scale(1.1);
z-index: 9;
border: 1px solid red;
box-shadow: 0 0 5px red;
}
}
}
}
</style>