JavaScript:在TextField中的Curser位置添加字符串OnkeyPress



我有以下代码:

<!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>

单击我的键盘上的返回键时,它将字符串<br>插入文本方面。不幸的是,该字符串将在Textarea内容的末尾插入,而不是在光标位置。

有人知道我需要做什么才能在光标位置插入字符串<br>

此解决方案应该完成工作!

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);
  }
}

最新更新