jQuery Set Cursor Position in Text Area

前端 未结 16 1485
无人共我
无人共我 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:07

    The solutions here are right except for the jQuery extension code.

    The extension function should iterate over each selected element and return this to support chaining. Here is the a correct version:

    $.fn.setCursorPosition = function(pos) {
      this.each(function(index, elem) {
        if (elem.setSelectionRange) {
          elem.setSelectionRange(pos, pos);
        } else if (elem.createTextRange) {
          var range = elem.createTextRange();
          range.collapse(true);
          range.moveEnd('character', pos);
          range.moveStart('character', pos);
          range.select();
        }
      });
      return this;
    };
    

提交回复
热议问题