码迷,mamicode.com
首页 > Web开发 > 详细

js中replace方法光标不跳最后(VX)

时间:2017-06-17 22:29:58      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:结束   ext   char   create   return   func   理解   position   inpu   

$("#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 = texv;

    //设置光标位置
    $scope.setTxt1CursorPosition(this, Txt1Curs - 2);

   } else if (texv != this.value) {

    this.value = 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)

标签:结束   ext   char   create   return   func   理解   position   inpu   

原文地址:http://www.cnblogs.com/xianyubuxian/p/7041411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!