JavaScript:在textfield中的光标位置添加字符串onkeypress

时间:2017-09-23 22:41:10

标签: javascript jquery html textarea cursor-position

我有以下代码:

<!DOCTYPE html>
<html>
<head>
<script>function handleEnter(e){messageVar=document.form.main_text.value,13==e.keyCode&&(document.form.main_text.value=messageVar+"<br>")}</script>
</head>
<body>

<form name="form">

<textarea style="width:300px;height:200px;" name="main_text" onkeypress="handleEnter(event)">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</textarea><br><br>

</form>

</body>
</html>

单击键盘上的返回键时,它会在textarea中插入字符串<br>。不幸的是,字符串将插入textarea内容的末尾而不是光标位置。

是否有人知道在光标位置插入字符串<br>需要做什么?

1 个答案:

答案 0 :(得分:0)

这个解决方案应该可以胜任!

function handleEnter(e){
  var myElement = document.form.main_text;
  // Get the caret position
  var position = document.form.main_text.selectionStart;

  if (e.keyCode===13) {
    // Disable the default action of the Enter button (make a line break)
    e.preventDefault();
    // Set the new value = Text Before the cursor + "<br>" + text after the cursor
    myElement.value = myElement.value.substring(0,position)+"<br>"+myElement.value.substring(position)
    // Set the caret at the new position after the <br> tag
    myElement.setSelectionRange(position+4,position+4);
  }
}