如何使用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);
我找到了一个适合我的解决方案:
$.fn.setCursorPosition = function(position){
if(this.length == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.length == 0) return this;
var input = this[0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
} else if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
$.fn.focusEnd = function(){
this.setCursorPosition(this.val().length);
return this;
}
现在你可以通过调用以下命令将焦点移动到任何元素的末尾:
$(element).focusEnd();
或者你指定位置。
$(element).setCursorPosition(3); // This will focus on the third character.
如果setSelectionRange不存在,您可以直接更改原型。
(function() {
if (!HTMLInputElement.prototype.setSelectionRange) {
HTMLInputElement.prototype.setSelectionRange = function(start, end) {
if (this.createTextRange) {
var range = this.createTextRange();
this.collapse(true);
this.moveEnd('character', end);
this.moveStart('character', start);
this.select();
}
}
}
})();
document.getElementById("input_tag").setSelectionRange(6, 7);
js小提琴链接
我知道这是一个非常老的帖子,但我认为我应该提供一个更简单的解决方案,只使用jQuery更新它。
function getTextCursorPosition(ele) {
return ele.prop("selectionStart");
}
function setTextCursorPosition(ele,pos) {
ele.prop("selectionStart", pos + 1);
ele.prop("selectionEnd", pos + 1);
}
function insertNewLine(text,cursorPos) {
var firstSlice = text.slice(0,cursorPos);
var secondSlice = text.slice(cursorPos);
var new_text = [firstSlice,"\n",secondSlice].join('');
return new_text;
}
使用ctrl-enter添加新行(就像在Facebook中):
$('textarea').on('keypress',function(e){
if (e.keyCode == 13 && !e.ctrlKey) {
e.preventDefault();
//do something special here with just pressing Enter
}else if (e.ctrlKey){
//If the ctrl key was pressed with the Enter key,
//then enter a new line break into the text
var cursorPos = getTextCursorPosition($(this));
$(this).val(insertNewLine($(this).val(), cursorPos));
setTextCursorPosition($(this), cursorPos);
}
});
我乐于接受批评。谢谢你!
更新:这个解决方案不允许正常的复制和粘贴功能的工作(即ctrl-c, ctrl-v),所以我将不得不编辑这在未来,以确保该部分再次工作。如果你知道怎么做,请在这里评论,我很乐意测试。谢谢。