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); //设置光标
    /*-----------------*/
  • 相关阅读:
    git clone失败
    矩阵相乘
    pandas中关于DataFrame 去除省略号
    Linux系统清除缓存
    Git 远程仓库 更新url
    看不到git远程分支
    c++
    undefined reference to symbol' pthread_create@@GLIBC_2.2.5'
    ssh 与远程机器保持心跳(linux)
    python 读取文件第一列 空格隔开的数据
  • 原文地址:https://www.cnblogs.com/juexin/p/9698129.html
Copyright © 2011-2022 走看看