如何使用jQuery设置文本字段中的光标位置?我有一个带内容的文本字段,并且我希望当用户聚焦在该字段上时,其光标被定位到某个偏移量。代码应该类似于:
$('#input').focus(function() {
$(this).setCursorPosition(4);
});
那个setCursorPosition函数的实现应该是什么样子?如果你有一个文本字段,内容为abcdefg,那么这个调用将导致光标位置如下所示:abcd**|**efg。Java有一个类似的函数,叫做setCaretPosition。JavaScript是否有类似的方法?
更新:我修改了CMS的代码,使其适用于jQuery,如下所示:
new function($) {
$.fn.setCursorPosition = function(pos) {
if (this.setSelectionRange) {
this.setSelectionRange(pos, pos);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
if(pos < 0) {
pos = $(this).val().length + pos;
}
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
$(this).get(0).setSelectionRange
和this.setSelectionRange
完全一样,只是更慢且更难读吗?在这里jQuery实际上没有做任何事情。 - bobince