
场景:格式化银行卡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); //设置光标
/*-----------------*/