jQuery Set Cursor Position in Text Area

前端 未结 16 1706
无人共我
无人共我 2020-11-21 11:42

How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when

16条回答
  •  无人及你
    2020-11-21 12:04

    Small modification to the code I found in bitbucket

    Code is now able to select/highlight with start/end points if given 2 positions. Tested and works fine in FF/Chrome/IE9/Opera.

    $('#field').caret(1, 9);
    

    The code is listed below, only a few lines changed:

    (function($) {
      $.fn.caret = function(pos) {
        var target = this[0];
        if (arguments.length == 0) { //get
          if (target.selectionStart) { //DOM
            var pos = target.selectionStart;
            return pos > 0 ? pos : 0;
          }
          else if (target.createTextRange) { //IE
            target.focus();
            var range = document.selection.createRange();
            if (range == null)
                return '0';
            var re = target.createTextRange();
            var rc = re.duplicate();
            re.moveToBookmark(range.getBookmark());
            rc.setEndPoint('EndToStart', re);
            return rc.text.length;
          }
          else return 0;
        }
    
        //set
        var pos_start = pos;
        var pos_end = pos;
    
        if (arguments.length > 1) {
            pos_end = arguments[1];
        }
    
        if (target.setSelectionRange) //DOM
          target.setSelectionRange(pos_start, pos_end);
        else if (target.createTextRange) { //IE
          var range = target.createTextRange();
          range.collapse(true);
          range.moveEnd('character', pos_end);
          range.moveStart('character', pos_start);
          range.select();
        }
      }
    })(jQuery)
    

提交回复
热议问题