如何使用jQuery设置文本字段中的光标位置?我有一个包含内容的文本字段,当用户聚焦于该字段时,我希望用户的光标定位在特定的偏移量上。代码看起来应该是这样的:
$('#input').focus(function() {
$(this).setCursorPosition(4);
});这个setCursorPosition函数的实现是什么样子的?如果您有一个包含内容abcdefg的文本字段,则此调用将导致光标被定位为以下位置:abcd**x**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);https://stackoverflow.com/questions/499126
复制相似问题