繁体   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