将输入123456898877766
改成1234 5678 7776 的4个一组的形式
原理:输入的时候道达个添加一个空格,删除到达空格的时候自动删除一个空格。
'form.bankCard'(newVal, oldVal){
let trims = newVal.replace(/\s/g, '')
if(!/^[0-9]*$/.test(trims)){
this.form.bankCard = oldVal;
}else if(newVal.length < oldVal.length){//删除
if(newVal.substr(-1) == ' '){//newVal.replace(/(\s*$)/g, "").length ==
this.form.bankCard = newVal.replace(/(\s*$)/g, '');
}
}else{//新增
this.form.bankCard = trims.replace(/(\d{4})(?=\d)/g, '$1 ');
}
}
方法1存在bug, 输入一部分之后在中间加入的话,光标会瞬间移动到后面
方法2:绑定在输入框的input事件中
原文
// 格式化卡號顯示,每4位加-
formatCardNumber (cardNum) {
// 获取input的dom对象,这里因为用的是element ui的input,所以需要这样拿到
const input = document.getElementsByTagName('input')[0]
// 获取当前光标的位置
const cursorIndex = input.selectionStart
// 字符串中光标之前-的个数
const lineNumOfCursorLeft = (cardNum.slice(0, cursorIndex).match(/ /g) || []).length
// 去掉所有-的字符串
const noLine = cardNum.replace(/ /g, '')
// 去除格式不对的字符并重新插入-的字符串
const newCardNum = noLine.replace(/\D+/g, '').replace(/(\d{4})/g, '$1 ').replace(/ $/, '')
// 改后字符串中原光标之前-的个数
const newLineNumOfCursorLeft = (newCardNum.slice(0, cursorIndex).match(/ /g) || []).length
// 光标在改后字符串中应在的位置
const newCursorIndex = cursorIndex + newLineNumOfCursorLeft - lineNumOfCursorLeft
// 赋新值,nextTick保证-不能手动输入或删除,只能按照规则自动填入
this.$nextTick(() => {
this.form.bankCard = newCardNum
// 修正光标位置,nextTick保证在渲染新值后定位光标
this.$nextTick(() => {
// selectionStart、selectionEnd分别代表选择一段文本时的开头和结尾位置
input.selectionStart = newCursorIndex
input.selectionEnd = newCursorIndex
})
})
},