如何使用jQuery在文本字段中的字符串末尾设置光标位置?

时间:2011-09-10 00:20:33

标签: javascript jquery focus cursor textfield

我正在使用jQuery 1.6,我有一个文本字段,我希望在字段获得焦点后将光标定位在字符串\ text的末尾。有没有琐碎或容易做到这一点?

目前我正在使用以下代码:

$jQ('#css_id_value').focus(function(){
    this.select();
});
$jQ('css_id_value').focus();

3 个答案:

答案 0 :(得分:3)

$('#foo').focus(function() {
    if (this.setSelectionRange) {
        this.setSelectionRange(this.value.length, this.value.length);
    } else if (this.createTextRange) {
        // IE
        var range = this.createTextRange();
        range.collapse(true);
        range.moveStart('character', this.value.length);
        range.moveEnd('character', this.value.length);
        range.select();
    }
});

答案 1 :(得分:0)

http://jsfiddle.net/hn8EY/

$("input").mouseup(function(){
    this.selectionStart = this.value.length;
    this.selectionEnd = this.value.length;
});

应该这样做。

或者(因为我不知道你在此之后是什么:P)

$("input").mouseup(function(){
    if($(this).not(".c").length) {
        this.selectionStart = this.value.length;
        this.selectionEnd = this.value.length;
        $(this).addClass("c");
    }
}).blur(function(){
    $(this).removeClass("c");
});

答案 2 :(得分:-1)

使用以下代码:

var FieldInput = $('#fieldName');
var FldLength= FieldInput.val().length;
FieldInput.focus();
FieldInput[0].setSelectionRange(FldLength, FldLength);

希望对你有所帮助

相关问题