如何使用jQuery在文本框中设置光标位置?我有一个带有内容的文本字段,并且我希望光标在焦点位于特定的偏移位置,该如何实现呢?

 

实现方法一:

这是一个jQuery解决方案:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if(\'selecti \' in this) {
            this.selecti  = 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();
        }
    });
};

有了这个,你可以做

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

 

实现方法二:

$.fn.setCursorPosition = function(position){
    if(this.length == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selecti , selectionEnd) {
    if(this.length == 0) return this;
    input = this[0];

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

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
            return this;
}

现在,您可以通过调用以下任何元素将焦点移至任何元素的结尾

$(element).focusEnd();
收藏 打印