在“contenteditable”div中的光标位置插入元素

问题描述 投票:0回答:1

在我的项目中,我试图用“contenteditable=true”将插入元素包装在一个 div 中。这个想法是用户可以随时在 div 中插入此元素,包括在文本中间,跟随光标位置,如

document.getSelection().getRangeAt(0).startOffset
。下面我展示了一个或多或少遵循我的逻辑的代码示例

function insert(text){
  let element = '<span>'+text+'</span>';
  let textarea = document.getElementById('textarea');
  textarea.focus();
  let range = document.getSelection().getRangeAt(0);
  /*From now on, I should have the code that inserts the "element variable" inside the div in the same position where the user puts the editing cursor, but unfortunately everything I tried gave some kind of error or simply didn't come close*/
}
.textarea{
  width: calc(100% - 20px);
  height: 200px;
  background: #f1f1f1;
  padding: 10px;
  border-radius: 10px;
  margin-bottom: 10px;
}
span{
  color: dodgerblue;
}
<div class="textarea" id="textarea" contenteditable></div>
<button onclick="insert('additional text')">Insert</button>

javascript html insert contenteditable text-editor
1个回答
0
投票
textarea.textContent = textarea.textContent.substring(0, window.getSelection().baseOffset) +
element +
textarea.textContent.substring(window.getSelection().extentOffset);
© www.soinside.com 2019 - 2024. All rights reserved.