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ì)來(lái)說(shuō)還是比較簡(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è)問(wèn)題的辦法就是記錄光標(biāo)的位置并在value值格式重置之后重新設(shè)置光標(biāo)的位置,好了,思路就是這樣的,話不多說(shuō),直接上代碼
// 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. python如何實(shí)現(xiàn)word批量轉(zhuǎn)HTML2. python excel和yaml文件的讀取封裝3. python3實(shí)現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)4. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊5. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問(wèn)題及解決6. 詳解docker pull 下來(lái)的鏡像都存到了哪里7. Docker鏡像管理常用操作代碼示例9. 關(guān)于 Android WebView 的內(nèi)存泄露問(wèn)題10. Python中內(nèi)建模塊collections如何使用
