首页 > 代码库 > js中replace方法光标不跳最后(VX)
js中replace方法光标不跳最后(VX)
$("#wetg_Left_ipt2").bind("input",function() {
//获取光标位置
var Txt1Curs = $scope.getTxt1CursorPosition(this);
var oldtexv = this.value;
//格式化字符串4位分割,去掉非字母、数字、/和-以外的字符
var texv = oldtexv.replace(/[^A-Za-z0-9/ - ] / g,‘‘).replace(/(\S{4})(?=\S)/g,‘$1 ‘);
if (this.value.length > texv.length) {
this.value = http://www.mamicode.com/texv;
//设置光标位置
$scope.setTxt1CursorPosition(this, Txt1Curs - 2);
} else if (texv != this.value) {
this.value = http://www.mamicode.com/texv;
if ((Txt1Curs - 1) % 5 == 4) {
//设置光标位置
$scope.setTxt1CursorPosition(this, Txt1Curs);
} else {
//设置光标位置
$scope.setTxt1CursorPosition(this, Txt1Curs - 1);
}
}
});
$scope.getTxt1CursorPosition = function(oTxt1) {
oTxt1.focus();
var cursurPosition = -1;
if (oTxt1.selectionStart) { //非IE浏览器
cursurPosition = oTxt1.selectionStart;
} else { //IE
var range = document.selection.createRange();
range.moveStart("character", -oTxt1.value.length);
cursurPosition = range.text.length;
}
return cursurPosition;
}
$scope.setTxt1CursorPosition = function(oTxt1, i) {
var cursurPosition = -1;
if (oTxt1.selectionStart) { //非IE浏览器
//selectionStart我的理解是文本选择的开始位置
oTxt1.selectionStart = i + 1;
//selectionEnd我的理解是文本选择的结束位置
oTxt1.selectionEnd = i + 1;
oTxt1.focus();
} else { //IE
var range = oTxt1.createTextRange();
range.move("character", i);
range.select();
}
}
js中replace方法光标不跳最后(VX)