input,textarea,使用repalce方法后,在输入框中输入文字后光标自动跳至文尾
解决方法:光标重定位
<textarea rows="4" cols="20" id="txtArea1" οnkeyup="if (event.keyCode == 32) inputNumberOnly(this)"></textarea>
function 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;
}
function 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();
}
}
function inputNumberOnly(obj) {
var pos = this.getCursorPos(obj); //保存原始光标位置
var temp = obj.value; //保存原始值
obj.value = obj.value.replace(' ', ' ')
this.defaultVal = obj.value;
pos = pos - (temp.length - obj.value.length); //当前光标位置
this.setCursorPos(obj, pos); //设置光标
}