如何使用jQuery在文本框中设置光标位置?我有一个带有内容的文本字段,并且我希望光标在焦点位于特定的偏移位置,该如何实现呢?
实现方法一:
这是一个jQuery解决方案:
$.fn.selectRange = function(start, end) {
if(end === undefined) {
end = start;
}
return this.each(function() {
if(\'selecti \' in this) {
this.selecti = start;
this.selectionEnd = end;
} else if(this.setSelectionRange) {
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd(\'character\', end);
range.moveStart(\'character\', start);
range.select();
}
});
};
有了这个,你可以做
$(\'#elem\').selectRange(3,5); // select a range of text
$(\'#elem\').selectRange(3); // set cursor position
实现方法二:
$.fn.setCursorPosition = function(position){
if(this.length == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selecti , selectionEnd) {
if(this.length == 0) return this;
input = this[0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd(\'character\', selectionEnd);
range.moveStart(\'character\', selecti );
range.select();
} else if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selecti , selectionEnd);
}
return this;
}
$.fn.focusEnd = function(){
this.setCursorPosition(this.val().length);
return this;
}
现在,您可以通过调用以下任何元素将焦点移至任何元素的结尾
$(element).focusEnd(); 继续阅读与本文标签相同的文章
上一篇 :
css元素浮动导致父元素高度为0的解决方法
-
第16问:Filecoin从DSN角度解读
2026-05-14栏目: 教程
-
C/C+从零基础到精通,究竟是如何快速完成的?其实只需要这6步!
2026-05-14栏目: 教程
-
谷歌再爆重大安全漏洞!华为却成最大赢家?网友:这谁还敢用!
2026-05-14栏目: 教程
-
Excel崩溃文件如何找回
2026-05-14栏目: 教程
-
又一外国巨头宣布退出中国,关闭120家店,网友:中国钱不好赚了!
2026-05-14栏目: 教程
