jQuery Set Cursor Position in Text Area

前端 未结 16 1499
无人共我
无人共我 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;
    };
    
    0 讨论(0)
  • 2020-11-21 12:09

    I'm using this: http://plugins.jquery.com/project/jCaret

    0 讨论(0)
  • 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);
    });
    <textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
    <br><input type="button" id="set-textarea" value="Set in textarea">
    <br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">
    <br><input type="button" id="set-input" value="Set in input">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

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

    0 讨论(0)
  • 2020-11-21 12:10

    I found a solution that works for me:

    $.fn.setCursorPosition = function(position){
        if(this.length == 0) return this;
        return $(this).setSelection(position, position);
    }
    
    $.fn.setSelection = function(selectionStart, selectionEnd) {
        if(this.length == 0) return this;
        var input = this[0];
    
        if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        } else if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }
    
        return this;
    }
    
    $.fn.focusEnd = function(){
        this.setCursorPosition(this.val().length);
                return this;
    }
    

    Now you can move the focus to the end of any element by calling:

    $(element).focusEnd();
    

    Or you specify the position.

    $(element).setCursorPosition(3); // This will focus on the third character.
    
    0 讨论(0)
  • 2020-11-21 12:14

    This worked for me on Safari 5 on Mac OSX, jQuery 1.4:

    $("Selector")[elementIx].selectionStart = desiredStartPos; 
    $("Selector")[elementIx].selectionEnd = desiredEndPos;
    
    0 讨论(0)
  • 2020-11-21 12:16

    I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

    $.fn.getCaret = function(n) {
        var d = $(this)[0];
        var s, r;
        r = document.createRange();
        r.selectNodeContents(d);
        s = window.getSelection();
        console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
        return s.anchorOffset;
    };
    
    $.fn.setCaret = function(n) {
        var d = $(this)[0];
        d.focus();
        var r = document.createRange();
        var s = window.getSelection();
        r.setStart(d.childNodes[0], n);
        r.collapse(true);
        s.removeAllRanges();
        s.addRange(r);
        console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
        return this;
    };
    

    Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

    Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

    Bests ;D

    0 讨论(0)
提交回复
热议问题