如何使用jQuery在文本字段中设置光标位置?我有一个包含内容的文本字段,我希望用户光标在关注字段时定位在某个偏移处.代码应该看起来像这样:
$('#input').focus(function() {
$(this).setCursorPosition(4);
});
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud) 我有这个在我的身体,它的工作原理
onLoad='document.forms.post.message.focus()'
Run Code Online (Sandbox Code Playgroud)
但是我需要将光标放在任何现有文本开头的textarea中,而不是放在最后.这就把它放在了最后.
请注意,我对JavaScript一无所知,所以请保持温和.
谢谢