【发布时间】:2023-03-15 12:00:01
【问题描述】:
如何使用 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 注释,函数应该迭代每个选定的元素并返回它。正确的代码在我的答案中。
-
@bobince 实际上也不完全正确。 'this' 不是 DOM 节点,而是 jQuery 对象。所以,$(this).get(0).setSelectionRange 与 this.get(0).setSelectionRange 相同,与 this.setSelectionRange 不同。
-
$(this)[0] 比 $(this).get(0) 快
-
查看本教程以获得完整的解决方案。 webdesignpluscode.blogspot.com/2017/05/…
标签: javascript jquery html textfield