0

I know it's pretty easy to focus an input using JavaScript/ jQuery, but is it possible to focus the input on a certain character?

So take this input:

inputExample

Would it be possible to focus the element and have the cursor be placed after the first sentence, for example?

4

1 回答 1

1

Sure :

$('#inputID').focus().get(0).setSelectionRange(12, 12);

works in most browsers, but older IE uses createTextRange and move().

FIDDLE

EDIT:

five minute plugin:

$.fn.setCaret = function(pos) {
    return this.each(function() {
        var elem = this,
            range;

        if (elem.createTextRange) {
            range = elem.createTextRange();
            range.move('character', pos);
        } else {
            if (elem.selectionStart !== undefined) {
                elem.setSelectionRange(pos, pos);
            }
        }
    });
}

to be called like:

$('#inputID').focus().setCaret(12);

FIDDLE

于 2013-05-21T16:07:14.693 回答