jQuery设置文本区域的光标位置

时间:2017-11-04
之前做一个代码提示的功能涉及到在文本框中插入文本的操作,需要获得当前光标位置插入文本,本文章向大家介绍jQuery如何设置文本区域的光标位置,需要的朋友可以参考一下。

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

实现方法一:

这是一个jQuery解决方案:

$.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();
        }
    });
};

有了这个,你可以做

$('#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(selectionStart, 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', 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;
}

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

$(element).focusEnd();