将文本插入光标所在的文本区域

时间:2016-05-16 14:21:45

标签: javascript html dom

我有以下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>

如何修改内容以将内容插入到光标位于textarea中的textarea中(而不是仅仅放在现有文本的末尾)?

1 个答案:

答案 0 :(得分:0)

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>