问题
I am using jQuery 1.6 and I have a text field for which I would like the cursor to be positioned at the end of the string\text after the field receives focus. Is there a trivial or easy to do this?
At this time I am using the following code:
$jQ('#css_id_value').focus(function(){
this.select();
});
$jQ('css_id_value').focus();
回答1:
$('#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();
}
});
回答2:
http://jsfiddle.net/hn8EY/
$("input").mouseup(function(){
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
});
that should do it.
and alternatively (because I have no clue what your after here :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");
});
回答3:
Use below code:
var FieldInput = $('#fieldName');
var FldLength= FieldInput.val().length;
FieldInput.focus();
FieldInput[0].setSelectionRange(FldLength, FldLength);
Hope this help for you
来源:https://stackoverflow.com/questions/7368750/how-to-set-the-cursor-position-at-the-end-of-a-string-in-a-text-field-using-jque