如何使用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) Hai Guys,我想将光标设置在文本框上长度为14的位置,该文本框没有值..我知道最初光标将为0我希望它在14