如何使用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);
基于这个问题,当文本区域中有新行时,答案将不会完美地为ie和opera工作。
答案解释了如何在调用setSelectionRange之前调整selectionStart, selectionEnd。
我已经尝试了调整偏移从其他问题的解决方案由@AVProgrammer和它的工作。
function adjustOffset(el, offset) {
/* From https://stackoverflow.com/a/8928945/611741 */
var val = el.value, newOffset = offset;
if (val.indexOf("\r\n") > -1) {
var matches = val.replace(/\r\n/g, "\n").slice(0, offset).match(/\n/g);
newOffset += matches ? matches.length : 0;
}
return newOffset;
}
$.fn.setCursorPosition = function(position){
/* From https://stackoverflow.com/a/7180862/611741 */
if(this.lengh == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
/* From https://stackoverflow.com/a/7180862/611741
modified to fit https://stackoverflow.com/a/8928945/611741 */
if(this.lengh == 0) return this;
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();
selectionStart = adjustOffset(input, selectionStart);
selectionEnd = adjustOffset(input, selectionEnd);
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
$.fn.focusEnd = function(){
/* From https://stackoverflow.com/a/7180862/611741 */
this.setCursorPosition(this.val().length);
}
我必须让它为可满足的元素和jQuery工作,并认为有人可能想要它准备好使用:
$.fn.getCaret = function(n) {
var d = $(this)[0];
var s, r;
r = document.createRange();
r.selectNodeContents(d);
s = window.getSelection();
console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
return s.anchorOffset;
};
$.fn.setCaret = function(n) {
var d = $(this)[0];
d.focus();
var r = document.createRange();
var s = window.getSelection();
r.setStart(d.childNodes[0], n);
r.collapse(true);
s.removeAllRanges();
s.addRange(r);
console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
return this;
};
使用$(selector). getcaret()返回数字偏移量,$(selector). setcaret (num)建立偏移量并将焦点设置在元素上。
还有一个小提示,如果你从控制台运行$(selector). setcaret (num),它将返回console.log,但你不会看到焦点,因为它是在控制台窗口建立的。
D最好成绩;