使用vue框架实现
<input type="tel" v-model="bankcard" placeholder="请输入银行卡号">
data() { return { bankcard: '', count: 0 } }, watch: { bankcard (v, oldv) { this.$nextTick(() => { //获取输入框 let oTxt1 = document.getElementsByClassName('core-input')[0] // 操作中间位置 if (oTxt1.selectionStart < v.length) { this.savedStart = oTxt1.selectionStart if (v.length < oldv.length && v[this.savedStart - 1] === ' ') { this.savedStart = this.savedStart - 1 } else if (v.length > oldv.length && v[this.savedStart + 1] === ' ') { this.savedStart = this.savedStart + 1 } setTimeout(() => { oTxt1.selectionStart = this.savedStart oTxt1.selectionEnd = this.savedStart }, 0) this.count++ } else { // 正常输入的时候有的机型会出现光标错误问题,所以正常输入时候设置下光标到文字最后 if (this.count === 0) { setTimeout(() => { oTxt1.selectionStart = v.length oTxt1.selectionEnd = v.length }, 0) } else { this.count = 0 } } this.bankcard = this.bankcard.replace(/[^0-9]/g, '').replace(/(\S{4})(?=\S)/g, '$1 '); }) } },
补充知识:
HTMLInputElement.setSelectionRange
方法可以从一个被 focused 的 <input>
元素中选中特定范围的内容。
在较新的浏览器中,你可以通过一个可选的 selectionDirection 来指定文本选中过程中的方向。比如通过点击和拖动从结束位置往起始位置选中一个字符串。
每次调用这个这个方法会更新 HTMLInputElement 的 selectionStart
, selectionEnd
,和 selectionDirection
属性。
语法
inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);
参数
selectionStart
被选中的第一个字符的位置。
selectionEnd
被选中的最后一个字符的 下一个 位置。
selectionDirection (可选)
一个指明选择方向的字符串,有"forward","backward"和"none" 3个可选值, 分别表示"从前往后", "从后往前"和"选择方向未知或不重要"。