You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在带contenteditable属性的div光标位置插入元素?

解决contenteditable div光标位置插入元素的问题

你需要的核心是直接操作DOM元素和Range对象,而非使用HTML字符串拼接。以下是修正后的完整实现:

修正后的JavaScript代码

function insert(text) {
  // 创建目标span元素,而非转义的HTML字符串
  const span = document.createElement('span');
  span.textContent = text;
  
  const editableDiv = document.getElementById('textarea');
  editableDiv.focus();
  
  const selection = document.getSelection();
  if (selection.rangeCount === 0) return;
  
  const range = selection.getRangeAt(0);
  // 清除当前选中的内容(如果存在)
  range.deleteContents();
  // 将span插入到光标/选中位置
  range.insertNode(span);
  
  // 把光标移到插入元素的后方,方便继续编辑
  range.setStartAfter(span);
  range.setEndAfter(span);
  selection.removeAllRanges();
  selection.addRange(range);
}

对应的CSS和HTML

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

关键说明

  • 避免用HTML字符串拼接:直接创建DOM元素span,比操作innerHTML更安全,不会破坏原有DOM结构,也能精准定位插入位置。
  • Range对象的核心操作:deleteContents()清除选中内容(实现替换选中区域的效果),insertNode()将元素插入到光标所在的Range位置。
  • 光标位置调整:插入元素后主动将光标移到元素后方,保证用户可以继续流畅编辑,提升体验。

内容的提问来源于stack exchange,提问作者Emanoel José

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:07:54