因为你在keyup的时候,重新给input赋值了,所以光标会定位到最后。
直接上代码。
const getCursortPosition = (ctrl) => {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
// 设置光标位置
const setCaretPosition = (ctrl, pos) => {
if(ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
// 光标定位
const dealKeyup = (that) => {
var pos = getCursortPosition(that);
setCaretPosition(that,pos - 1);
}