使用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個可選值, 分別表示"從前往後", "從後往前"和"選擇方向未知或不重要"。