jQuery Set Cursor Position in Text Area

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

    You can directly change the prototype if setSelectionRange does not exist.

    (function() {
        if (!HTMLInputElement.prototype.setSelectionRange) {
            HTMLInputElement.prototype.setSelectionRange = function(start, end) {
                if (this.createTextRange) {
                    var range = this.createTextRange();
                    this.collapse(true);
                    this.moveEnd('character', end);
                    this.moveStart('character', start);
                    this.select();
                }
            }
        }
    })();
    document.getElementById("input_tag").setSelectionRange(6, 7);
    

    jsFiddle link

提交回复
热议问题