解決replace格式替換後光標定位問題

場景:格式化銀行卡444格式 手機號344格式 身份證號684格式 校驗數據格式,replace後光標定位錯亂 或光標一直定位在最後

解決,只針對input,代碼用的vue:

獲取光標位置:

getCursorPos(obj) {
      var CaretPos = 0; // IE Support
      if (document.selection) {
        obj.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -obj.value.length);
        CaretPos = Sel.text.length;
      } else if (obj.selectionStart || obj.selectionStart == '0') // Firefox/Safari/Chrome/Opera support
        CaretPos = obj.selectionEnd;
      return CaretPos;
    },

設置光標位置:

setCursorPos(obj, pos) {
      if (obj.setSelectionRange) {//Firefox/Safari/Chrome/Opera
        obj.focus();
        obj.setSelectionRange(pos, pos);
      } else if (obj.createTextRange) { // IE
        var range = obj.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
      }
    }

使用(obj當前input):

/*-----------------*/
      let obj = $event.target;
        var pos = this.getCursorPos(obj); //保存原始光標位置
        var temp = obj.value; //保存原始值
        obj.value = obj.value.replace(/\D/g, '').replace(/....(?!$)/g, '$& ');
        this.defaultVal = obj.value;
        pos = pos - (temp.length - obj.value.length); //當前光標位置
        this.setCursorPos(obj, pos); //設置光標
/*-----------------*/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章