Tan*_*tel 5 html javascript textbox
我正在尝试向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);
Run Code Online (Sandbox Code Playgroud)
上面的代码更新了textBox值,但没有将光标位置更新为新行.
(虽然当我单击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>
Run Code Online (Sandbox Code Playgroud)
使用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);
}
Run Code Online (Sandbox Code Playgroud)
我在聚焦后选择了文字.
function insertNewlineAndFocus() {
let textarea = document.getElementById("unicorn");
textarea.value = textarea.value + "\n";
textarea.setSelectionRange(textarea.value.length, textarea.value.length);
textarea.focus();
}Run Code Online (Sandbox Code Playgroud)
button {
display: block;
margin: 10px;
}
textarea {
min-width: 50%;
min-height: 100px;
margin: 10px;
}Run Code Online (Sandbox Code Playgroud)
<button onclick="insertNewlineAndFocus()">do it!</button>
<textarea id="unicorn">the most phenomenal text, really, its the best</textarea>Run Code Online (Sandbox Code Playgroud)