【问题标题】:How to set the cursor position at the end of a string in a text field using jQuery?如何使用jQuery在文本字段中的字符串末尾设置光标位置?
【发布时间】:2011-09-10 00:20:33
【问题描述】:
我正在使用 jQuery 1.6,并且我有一个文本字段,我希望在该字段获得焦点后将光标定位在 string\text 的末尾。有没有小事或容易做到这一点?
此时我正在使用以下代码:
$jQ('#css_id_value').focus(function(){
this.select();
});
$jQ('css_id_value').focus();
【问题讨论】:
标签:
javascript
jquery
focus
cursor
textfield
【解决方案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;
});
应该这样做。
或者(因为我不知道你在这里之后是什么: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】:
使用下面的代码:
var FieldInput = $('#fieldName');
var FldLength= FieldInput.val().length;
FieldInput.focus();
FieldInput[0].setSelectionRange(FldLength, FldLength);
希望对你有所帮助