jQuery Set Cursor Position in Text Area

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

    Based on this question, the answer will not work perfectly for ie and opera when there is new line in the textarea. The answer explain how to adjust the selectionStart, selectionEnd before calling setSelectionRange.

    I have try the adjustOffset from the other question with the solution proposed by @AVProgrammer and it work.

    function adjustOffset(el, offset) {
        /* From https://stackoverflow.com/a/8928945/611741 */
        var val = el.value, newOffset = offset;
        if (val.indexOf("\r\n") > -1) {
            var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
            newOffset += matches ? matches.length : 0;
        }
        return newOffset;
    }
    
    $.fn.setCursorPosition = function(position){
        /* From https://stackoverflow.com/a/7180862/611741 */
        if(this.lengh == 0) return this;
        return $(this).setSelection(position, position);
    }
    
    $.fn.setSelection = function(selectionStart, selectionEnd) {
        /* From https://stackoverflow.com/a/7180862/611741 
           modified to fit https://stackoverflow.com/a/8928945/611741 */
        if(this.lengh == 0) return this;
        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();
            selectionStart = adjustOffset(input, selectionStart);
            selectionEnd = adjustOffset(input, selectionEnd);
            input.setSelectionRange(selectionStart, selectionEnd);
        }
    
        return this;
    }
    
    $.fn.focusEnd = function(){
        /* From https://stackoverflow.com/a/7180862/611741 */
        this.setCursorPosition(this.val().length);
    }
    

提交回复
热议问题