在textBox javascript中设置光标位置

时间:2016-11-13 21:27:42

标签: javascript html 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);

上面的代码更新了textBox值,但没有将光标位置更新为新行。

(虽然当我点击textBox外部并再次单击textBox内部时它会更新光标位置,但是当用户已经在编辑textBox时却没有。)

2 个答案:

答案 0 :(得分:7)

这也适用于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);
}

JS Bin example

我在聚焦后选择文字。

答案 1 :(得分:4)

&#13;
&#13;
function insertNewlineAndFocus() {
  let textarea = document.getElementById("unicorn");
  textarea.value = textarea.value + "\n";
  textarea.setSelectionRange(textarea.value.length, textarea.value.length);
  textarea.focus();
}
&#13;
button {
  display: block;
  margin: 10px;
}
textarea {
  min-width: 50%;
  min-height: 100px;
  margin: 10px;
}
&#13;
<button onclick="insertNewlineAndFocus()">do it!</button>
<textarea id="unicorn">the most phenomenal text, really, its the best</textarea>
&#13;
&#13;
&#13;