国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

JavaScript實現手機號碼 3-4-4格式并控制新增和刪除時光標的位置

瀏覽:21日期:2023-06-20 14:49:39

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格式內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 平武县| 芦山县| 准格尔旗| 剑河县| 余江县| 桃园市| 峨眉山市| 奇台县| 行唐县| 汶川县| 兰溪市| 泊头市| 绵阳市| 林西县| 洱源县| 瑞昌市| 海伦市| 望江县| 安顺市| 鸡泽县| 巴林左旗| 那坡县| 黄平县| 东乡县| 尚志市| 尖扎县| 英山县| 兴安县| 儋州市| 丰顺县| 中超| 岑溪市| 达拉特旗| 富宁县| 桃园市| 鄯善县| 高唐县| 贵阳市| 玛多县| 昭觉县| 宝兴县|