要“聚焦特定的文本框而不选择它”:我会使用修补的 jquery 插件 jquery-fieldselection 的一部分
使用它你可以打电话
$('#my_text_input').setSelection({"start":0, "end":0}); // leaves the cursor at the left
或者使用这个将光标放在文本末尾的简化版本(默认情况下)
(function() {
var fieldSelection = {
setSelection: function() {
var e = (this.jquery) ? this[0] : this, len = this.val().length || ;
var args = arguments[0] || {"start":len, "end":len};
/* mozilla / dom 3.0 */
if ('selectionStart' in e) {
if (args.start != undefined) {
e.selectionStart = args.start;
}
if (args.end != undefined) {
e.selectionEnd = args.end;
}
e.focus();
}
/* exploder */
else if (document.selection) {
e.focus();
var range = document.selection.createRange();
if (args.start != undefined) {
range.moveStart('character', args.start);
range.collapse();
}
if (args.end != undefined) {
range.moveEnd('character', args.end);
}
range.select();
}
return this;
}
};
jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });
})();
这样使用:
$('#my_text_input').setSelection(); // leaves the cursor at the right