zoukankan      html  css  js  c++  java
  • 解决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); //设置光标
    /*-----------------*/
  • 相关阅读:
    barcode制作条形码及破解
    软件敏捷架构师
    软件需求分析三步走
    GDI+显示GIF动画
    CSpinButtonCtrl的弱智问题
    [C++] STL里面的map
    [C#] 再议Exception
    [C++] unsigned是麻烦制造者
    用GDI+转BMP为WMF、EXIF、EMF格式
    [C++] 编译时的warning
  • 原文地址:https://www.cnblogs.com/juexin/p/9698129.html
Copyright © 2011-2022 走看看