簡體   English   中英

在 Cursor 所在的 Textarea 中插入文本

[英]Insert Text Into Textarea Where Cursor Is

我有以下 JS,它在當前 textarea 中的任何內容的末尾將一些內容插入到 textarea 中。 這一切都適用於以下代碼:

<script>
if (opener.document.post.sMessage.createTextRange && opener.document.post.sMessage.caretPos) {
  var caretPos = opener.document.post.sMessage.caretPos;
  caretPos.text = '\n\n![](http://example.com/image.png)';
} else {
opener.document.post.sMessage.value += '\n\n![](http://example.com/image.png)';
}
self.close(); //close popup
</script>

如何修改以將內容插入 cursor 所在的文本區域(而不是僅在現有文本的末尾)?

使用 VanillaJS 的解決方案

 function addContentAtCursorFunc( elem, newContent ) { if (elem.selectionStart || elem.selectionStart == '0') { let _startSelection = elem.selectionStart; let _endSelection = elem.selectionEnd; elem.value = elem.value.substring(0, _startSelection) + newContent + elem.value.substring(endPos, elem.value.length); } else { elem.value += newContent; } } const button = document.getElementById('myBtn'); const textarea = document.getElementById('myTextarea'); button.addEventListener('click', event => { addContentAtCursorFunc( textarea , " *| I'M NEW CONTENT! |* ") return false });
 <textarea id="myTextarea" cols="40" rows="3">Select some of this text and then hit the button.</textarea> <button id="myBtn">Type some stuff</button>

沒有足夠的聲譽來發表評論,但我相信@GMKHussain 的回答包含錯字。

我認為在行+ elem.value.substring(endPos, elem.value.length); endPos應替換為_endSelection+ elem.value.substring(_endSelection, elem.value.length);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM