JavaScript實現(xiàn)手機號碼 3-4-4格式并控制新增和刪除時光標的位置
JavaScript實現(xiàn)手機號碼 3-4-4格式
手機號實現(xiàn)3-4-4格式相對來說還是比較簡單的,監(jiān)聽input事件,實時的獲取手機號碼,然后根據(jù)手機號碼的長度做截取和拼接的操作,即可實現(xiàn)手機格式的處理,實現(xiàn)格式的處理之后,我們還需要支持在指定光標進行新增和刪除操作的時候光標不移動到最后面,因為手機號的格式使我們重置的,監(jiān)聽input事件重新賦值之后光標會移動到最后一位,解決這個問題的辦法就是記錄光標的位置并在value值格式重置之后重新設(shè)置光標的位置,好了,思路就是這樣的,話不多說,直接上代碼
// 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è)置光標的位置
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實現(xiàn)手機號碼 3-4-4格式并控制新增和刪除時光標的位置的文章就介紹到這了,更多相關(guān)js 手機號碼3-4-4格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript動態(tài)改變HTML頁面元素例如添加或刪除
HTML頁面元素可以通過js動態(tài)改變,比如可以向HTML中添加元素或刪除某個元素,下面為示例代碼,感興趣的朋友不要錯過2014-08-08
微信小程序?qū)W習筆記之登錄API與獲取用戶信息操作圖文詳解
這篇文章主要介紹了微信小程序?qū)W習筆記之登錄API與獲取用戶信息操作,結(jié)合實例形式分析了微信小程序登陸請求及后臺交互相關(guān)操作技巧,并結(jié)合圖文形式進行說明,需要的朋友可以參考下2019-03-03
javascript 漢字轉(zhuǎn)拼音實現(xiàn)代碼
主要是提前定義了很多文字,這樣的方法不是很是,如果庫中沒有這個詞,是看不到相關(guān)信息的。2009-12-12
Javascript實現(xiàn)關(guān)聯(lián)數(shù)據(jù)(Linked Data)查詢及注意細節(jié)
DBpedia對Wikipedia的數(shù)據(jù)變成Linked Data形式,使得機器也能讀懂并自由獲得這些數(shù)據(jù);本文的主要目的是利用Javascript從DBpedia中獲取我們想要的數(shù)據(jù),感興趣的朋友可以參考下,希望可以幫助到你2013-02-02

