我正在尝试使用以下代码向 textBox 添加新行并使用 JavaScript 中的新行字符更新 textBox 值:
ele.value = ele.value + "\n";
ele.focus();
// To update cursor position to recently added character in textBox
ele.setSelectionRange(value.length, value.length);
上面的代码更新了文本框的值,但没有将光标位置更新到新行。
(尽管当我在 textBox 外部单击并再次在 textBox 内部单击时它会更新光标位置,但当 textBox 已被用户编辑时则不会。)
最佳答案
这也适用于 Firefox:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<textarea id="myText" rows="4" cols="50" onkeypress="">The rain in Spain falls mainly on the plains.</textarea>
<br>
<button onclick="updateText()">Update</button>
</body>
</html>
Javascript:
function updateText(e) {
var ele = document.getElementById('myText');
var newVal = 'Old McDonald had a farm.\n';
ele.value = newVal;
ele.focus();
// To update cursor position to recently added character in textBox
ele.setSelectionRange(newVal.length, newVal.length);
}
我在聚焦后选择文本。
关于javascript - 在文本框javascript中设置光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40579014/