有人知道如何将文本框中的键盘插入符号移动到特定位置吗?
例如,如果一个文本框(例如,输入元素,而不是文本区域)中有50个字符,而我想将插入符号放在字符20之前,我该如何操作呢?
这与这个问题不同:jQuery Set Cursor Position in Text Area,它需要jQuery.
有人知道如何将文本框中的键盘插入符号移动到特定位置吗?
例如,如果一个文本框(例如,输入元素,而不是文本区域)中有50个字符,而我想将插入符号放在字符20之前,我该如何操作呢?
这与这个问题不同:jQuery Set Cursor Position in Text Area,它需要jQuery.
摘自Josh Stodola的100
一个泛型函数,允许您在文本框或文本区域的任何位置插入插入符号:
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
第一个预期参数是要插入键盘插入符号的元素的ID.如果找不到元素,则不会发生任何事情(显然).第二个参数是插入符号位置索引.Zero会将键盘插入符号放在开头.如果传递的数字大于"元素"值中的字符数,则会将键盘插入符号置于末尾.
在IE6及以上版本、Firefox 2、Opera 8、Netscape 9、SeaMonkey和Safari上测试.不幸的是,在Safari上,它不能与onfocus活动结合使用).
使用上面的函数强制键盘插入符号在页面上的所有文本区域接收焦点时跳到它们的末尾的示例:
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);