gpt4 book ai didi

javascript - 在 html 文本框中设置键盘插入符号位置

转载 作者:IT老高 更新时间:2023-10-28 13:17:07 26 4
gpt4 key购买 nike

有人知道如何将文本框中的键盘插入符号移动到特定位置吗?

例如,如果一个文本框(例如输入元素,而不是文本区域)中有 50 个字符,我想将插入符号放在第 20 个字符之前,我该怎么做?

这与这个问题不同:jQuery Set Cursor Position in Text Area ,这需要 jQuery。

最佳答案

摘自乔什·斯托多拉的 Setting keyboard caret Position in a Textbox or TextArea with Javascript

一个通用函数,可让您在所需的文本框或文本区域的任何位置插入插入符号:

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。如果无法找到该元素,则什么都不会发生(显然)。第二个参数是插入符号位置索引。零会将键盘插入符号放在开头。如果您传递的数字大于元素值中的字符数,它将把键盘插入符号放在末尾。

在 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);

关于javascript - 在 html 文本框中设置键盘插入符号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/512528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com