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

JavaScript實現手機號碼 3-4-4格式
手機號實現3-4-4格式相對來說還是比較簡單的,監聽input事件,實時的獲取手機號碼,然後根據手機號碼的長度做截取和拼接的操作,即可實現手機格式的處理,實現格式的處理之後,我們還需要支持在指定光標進行新增和刪除操作的時候光標不移動到最後面,因爲手機號的格式使我們重置的,監聽input事件重新賦值之後光標會移動到最後一位,解決這個問題的辦法就是記錄光標的位置並在value值格式重置之後重新設置光標的位置,好了,思路就是這樣的,話不多說,直接上代碼

// 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;
 }
 // 重新賦值之後設置光標的位置
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);
    },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章