jQuery Set Cursor Position in Text Area

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

    Here's a jQuery solution:

    $.fn.selectRange = function(start, end) {
        if(end === undefined) {
            end = start;
        }
        return this.each(function() {
            if('selectionStart' in this) {
                this.selectionStart = start;
                this.selectionEnd = end;
            } else if(this.setSelectionRange) {
                this.setSelectionRange(start, end);
            } else if(this.createTextRange) {
                var range = this.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            }
        });
    };
    

    With this, you can do

    $('#elem').selectRange(3,5); // select a range of text
    $('#elem').selectRange(3); // set cursor position
    
    • JsFiddle
    • JsBin

提交回复
热议问题