您好,登錄后才能下訂單哦!
這篇文章主要講解了JavaScript如何實(shí)現(xiàn)手機(jī)號(hào)碼3-4-4格式并控制新增和刪除時(shí)光標(biāo)的位置,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
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" class="life-input" v-model="value" :maxlength="13" :placeholder="哈哈哈哈哈" :pattern="[0-9]*" @input="onInput" /> // javascript onInput(){ 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); },
看完上述內(nèi)容,是不是對(duì)JavaScript如何實(shí)現(xiàn)手機(jī)號(hào)碼3-4-4格式并控制新增和刪除時(shí)光標(biāo)的位置有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。