jQuery Set Cursor Position in Text Area

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

    I have two functions:

    function setSelectionRange(input, selectionStart, selectionEnd) {
      if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
      }
      else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
      }
    }
    
    function setCaretToPos (input, pos) {
      setSelectionRange(input, pos, pos);
    }
    

    Then you can use setCaretToPos like this:

    setCaretToPos(document.getElementById("YOURINPUT"), 4);
    

    Live example with both a textarea and an input, showing use from jQuery:

    function setSelectionRange(input, selectionStart, selectionEnd) {
      if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
      } else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
      }
    }
    
    function setCaretToPos(input, pos) {
      setSelectionRange(input, pos, pos);
    }
    
    $("#set-textarea").click(function() {
      setCaretToPos($("#the-textarea")[0], 10)
    });
    $("#set-input").click(function() {
      setCaretToPos($("#the-input")[0], 10);
    });
    
    


    As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last here; Stack Snippets don't support IE8).

提交回复
热议问题