呈現(xiàn)的效果大概是這樣的,驗(yàn)證碼框和密碼框都是可以使用這套代碼的,只是修改樣式而已.
主要功能是可以實(shí)現(xiàn)輸入數(shù)字以后(用正則限定了只可以輸入數(shù)字),光標(biāo)自動(dòng)下跳,刪除自動(dòng)上跳.鍵入以后輸入框原數(shù)據(jù)清空,未做更改,失焦之后輸入框數(shù)據(jù)不變.
找了很久沒(méi)找到合適的,最終還是自己完成了一個(gè).代碼注釋也寫(xiě)的比較清晰.
代碼如下(本人編程能力一般所以寫(xiě)的也比較簡(jiǎn)單通俗,如果真的被大佬看到,有什么不好的地方請(qǐng)馬上指出謝謝):
html部分
<div class="verifyCode">
<div class="verifyCodeItem" v-for="p in inputNums" :key="p">
<input
type="text"
@input="inputFun($event,p)"
@focus="onInputIn($event,p)"
@blur="onInputOut($event,p)"
@keyup.delete="onInputDelete($event,p)"
:value="code[p-1]"
:class="{success: code[p-1]===0}"
/>
<span v-if="p==2">億</span>
<span v-if="p==6">萬(wàn)</span>
<span v-if="p==10">.</span>
<span v-if="p==12">份</span>
</div>
</div>
js部分
export default {
props: {
inputNums: {
type: Number,
default: 12
},
value: {
type: String,
default: '000000000000'
},
realValue: {
type: String
}
},
data () {
return {
code: this.value.split(''),
historyVal: '',
isChange: false
}
},
methods: {
// 獲取焦點(diǎn)時(shí)
onInputIn (e, p) {
this.historyVal = this.code[p - 1]
this.$set(this.code, p - 1, '')
},
// 失去焦點(diǎn)時(shí)
onInputOut (e, p) {
if (this.isChange) {
this.isChange = false
this.historyVal = this.code[p - 1]
} else {
this.$set(this.code, p - 1, this.historyVal)
}
// 失去焦點(diǎn)時(shí)傳遞當(dāng)前code值
let newVal = this.code.map(item => {
if (item === '' || item === 'underfined') {
item = '0'
}
return item
})
this.$emit('getVal', (newVal.join('') / 100).toString())
},
// 鍵入內(nèi)容時(shí)
inputFun (e, p) {
let ele = e.target
let siblingsNode = ele.parentNode.parentNode.children
// 獲取填入的值,并且存入
let value = ele.value.replace(/[^\d]/g, '').slice(-1)
ele.parentNode.value = value
this.$set(this.code, p - 1, value)
// 邊界值處理
if (p >= siblingsNode.length - 1) {
p = siblingsNode.length - 1
}
// 記錄更改,下一個(gè)元素獲得焦點(diǎn)
if (value) {
this.isChange = true
siblingsNode[p].children[0].focus()
}
},
// 按下刪除鍵(delete/backspace)時(shí)
onInputDelete (e, p) {
let ele = e.target
let siblingsNode = ele.parentNode.parentNode.children
// 當(dāng)前光標(biāo)所指的位置數(shù)值是0
this.historyVal = 0
this.code[p - 1] = 0
// 邊界值處理
if (p <= 2) {
p = 2
}
siblingsNode[p - 2].children[0].focus()
}
}
}
css部分
@mixin border() {
border: 0.5px solid #dbd8d2;
background-color: #ebe8e2;
box-shadow: inset 0px 15px 10px -15px #c6c3be;
}
.verifyCode {
display: flex;
color: #38383b;
.verifyCodeItem {
display: flex;
align-items: baseline;
> span {
margin: 0 5px;
}
}
input {
@include border();
font-size: 14px;
margin-left: 2px;
width: 30px;
height: 40px;
border-radius: 5px;
text-align: center;
color: #a08d79;
font-size: 20px;
&:first {
margin-left: 0;
}
&:focus {
outline-color: #a08d79;
outline-width: 0.5px;
}
&.success {
border-color: #dbd8d2;
border-width: 0.5px;
transition: border-color 0.5s;
outline: none;
}
}
}