JavaScript實現手機號碼 3-4-4格式并控制新增和刪除時光標的位置
JavaScript實現手機號碼 3-4-4格式
手機號實現3-4-4格式相對來說還是比較簡單的,監聽input事件,實時的獲取手機號碼,然后根據手機號碼的長度做截取和拼接的操作,即可實現手機格式的處理,實現格式的處理之后,我們還需要支持在指定光標進行新增和刪除操作的時候光標不移動到最后面,因為手機號的格式使我們重置的,監聽input事件重新賦值之后光標會移動到最后一位,解決這個問題的辦法就是記錄光標的位置并在value值格式重置之后重新設置光標的位置,好了,思路就是這樣的,話不多說,直接上代碼
// An highlighted block <input ref='inputRef' v-model='value' :maxlength='13' :placeholder='哈哈哈哈哈' :pattern='[0-9]*' @input='onInput' />// javascriptonInput(){ val = this.value.replace(/D/g, ’’).substring(0, 11); const nowIndex = this.getCursortPosition(this.$refs.inputRef); if (valueLen > 3 && valueLen < 8) { this.value = `${val.substr(0, 3)} ${val.substr(3)}`; } else if (valueLen >= 8) { this.value = `${val.substr(0, 3)} ${val.substr( 3, 4 )} ${val.substr(7)}`; } else { this.value = val; } // 重新賦值之后設置光標的位置this.setCurIndex(nowIndex, this.curInputObj.value);}, getCursortPosition(element) { let CaretPos = 0; if (document.selection) { // 支持IE element.focus(); const Sel = document.selection.createRange(); Sel.moveStart(’character’, -element.value.length); CaretPos = Sel.text.length; } else if (element.selectionStart || element.selectionStart === ’0’){ // 支持firefox CaretPos = element.selectionStart; } return CaretPos }, setCurIndex(nowIndex, value) { const len = value.length; setTimeout(() => { let pos = nowIndex; // 新增操作 if (len > this.oldLen) { if (nowIndex === 4 || nowIndex === 9) { pos += 1; } } else if (len > this.oldLen) { // 刪除操作 if (nowIndex === 4 || nowIndex === 9) { pos -= 1; } } this.$refs.inputRef.selectionStart = pos; this.$refs.inputRef.selectionEnd = pos; this.oldLen = this.curInputObj.value.length; }, 0); },
總結
到此這篇關于JavaScript實現手機號碼 3-4-4格式并控制新增和刪除時光標的位置的文章就介紹到這了,更多相關js 手機號碼3-4-4格式內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: