JavaScript實(shí)現(xiàn)手機(jī)號(hào)碼 3-4-4格式并控制新增和刪除時(shí)光標(biāo)的位置
JavaScript實(shí)現(xiàn)手機(jī)號(hào)碼 3-4-4格式
手機(jī)號(hào)實(shí)現(xiàn)3-4-4格式相對(duì)來說還是比較簡(jiǎn)單的,監(jiān)聽input事件,實(shí)時(shí)的獲取手機(jī)號(hào)碼,然后根據(jù)手機(jī)號(hào)碼的長(zhǎng)度做截取和拼接的操作,即可實(shí)現(xiàn)手機(jī)格式的處理,實(shí)現(xiàn)格式的處理之后,我們還需要支持在指定光標(biāo)進(jìn)行新增和刪除操作的時(shí)候光標(biāo)不移動(dòng)到最后面,因?yàn)槭謾C(jī)號(hào)的格式使我們重置的,監(jiān)聽input事件重新賦值之后光標(biāo)會(huì)移動(dòng)到最后一位,解決這個(gè)問題的辦法就是記錄光標(biāo)的位置并在value值格式重置之后重新設(shè)置光標(biāo)的位置,好了,思路就是這樣的,話不多說,直接上代碼
// 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; } // 重新賦值之后設(shè)置光標(biāo)的位置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); },
總結(jié)
到此這篇關(guān)于JavaScript實(shí)現(xiàn)手機(jī)號(hào)碼 3-4-4格式并控制新增和刪除時(shí)光標(biāo)的位置的文章就介紹到這了,更多相關(guān)js 手機(jī)號(hào)碼3-4-4格式內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算2. Spring如何集成ibatis項(xiàng)目并實(shí)現(xiàn)dao層基類封裝3. JS圖片懶加載庫(kù)VueLazyLoad詳解4. IDEA 2020.1.2 安裝教程附破解教程詳解5. Python 解決火狐瀏覽器不彈出下載框直接下載的問題6. Java利用TCP協(xié)議實(shí)現(xiàn)客戶端與服務(wù)器通信(附通信源碼)7. 使用AJAX(包含正則表達(dá)式)驗(yàn)證用戶登錄的步驟8. Java實(shí)現(xiàn)的迷宮游戲9. Java PreparedStatement用法詳解10. django queryset相加和篩選教程

網(wǎng)公網(wǎng)安備