Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
(摘自Josh Stodola的使用Javascript在Textbox或TextArea中设置键盘插入符号的位置)
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
(泛型函数,可让您将插入符号插入所需的文本框或文本区域的任何位置:)
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();
}
}
}
The first expected parameter is the ID of the element you wish to insert the keyboard caret on.
(第一个预期参数是您希望插入键盘插入符号的元素的ID。)
If the element is unable to be found, nothing will happen (obviously).(如果找不到该元素,则不会发生任何事情(显然)。)
The second parameter is the caret positon index.(第二个参数是插入号位置索引。)
Zero will put the keyboard caret at the beginning.(零将把键盘插入符号放在开头。)
If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.(如果您传递的数字大于elements值中的字符数,它将把键盘插入符号放在最后。)
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari.
(在IE6及更高版本,Firefox 2,Opera 8,Netscape 9,SeaMonkey和Safari上进行了测试。)
Unfortunately on Safari it does not work in combination with the onfocus event).(不幸的是,在Safari上,它无法与onfocus事件结合使用。)
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
(使用上述功能强制键盘插入符号在获得焦点时跳至页面上所有文本区域的末尾的示例:)
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…