JS 银行卡格式输入框
效果
http://www.oujin.fun/webPage/inputTest/index.html#/
代码
<template>
<div class="content row-center">
<div class="boxStyle4 borderStyle row-center">
<input @input="limitLength" @change="checkCardInput" v-model="value" class="inputStyle"/>
</div>
</div>
</template>
data () {
return {
value: ''
}
},
methods: {
limitLength () {
this.value = this.value.replace(/-/g, '')
let length = this.value.length
if (length > 19) {
this.value = this.value.substring(0, 19)
}
},
checkCardInput () {
// 去除上次变形所遗留的'-'
this.value = this.value.replace(/-/g, '')
let length = this.value.length
// 将类数组对象转为数组对象
let list = Array.prototype.slice.call(this.value)
if (length > 4) {
for (let i = 0; i < length; i++) {
// 如果是第四位,且未被处理,且不是最后一位则不被处理
if ((i + 1) % 4 === 0 && list[i + 1] !== '-' && i !== length - 1) {
list[i] = String(list[i]) + '-'
}
}
}
// 数组转字符串并去逗号
this.value = list.toString().replace(/,/g, '')
}
}