在textBox javascript中设置光标位置 [英] set cursor position in textBox javascript
本文介绍了在textBox javascript中设置光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向textBox添加新行,并使用以下代码在JavaScript中使用新行字符更新textBox值:
I am trying to add new line to textBox and update textBox value with new line character in JavaScript using following code:
ele.value = ele.value + "\n";
ele.focus();
// To update cursor position to recently added character in textBox
ele.setSelectionRange(value.length, value.length);
上面的代码更新了textBox值,但没有将光标位置更新为新行。
Above code updates textBox value but doesn't update cursor position to new line.
(虽然当我单击textBox外部并再次单击textBox内部时它会更新光标位置,但是当textBox已经被用户编辑时却没有。)
(Though it updates cursor position when I click outside of textBox and again click inside textBox, but not when textBox is already being edited by user.)
推荐答案
这也适用于Firefox:
This should work in Firefox as well:
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:
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);
}
我在聚焦后选择文本。
这篇关于在textBox javascript中设置光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文