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

如何获取contenteditable内光标所在div并点击按钮为其添加类

contenteditable容器内获取光标所在div并添加缩进类实现方案

核心逻辑是通过浏览器选区API获取光标位置,向上遍历找到contenteditable容器的直接子div,即为目标的currentDiv元素。

完整JS代码

$('button').on('click', function(){
  const selection = window.getSelection();
  // 无有效选区直接退出
  if (!selection.rangeCount) return;
  let targetNode = selection.anchorNode;
  // 光标落在文本节点时取父元素
  if (targetNode.nodeType === Node.TEXT_NODE) {
    targetNode = targetNode.parentElement;
  }
  const editableRoot = document.querySelector('div[contenteditable]');
  // 向上遍历直到找到contenteditable的直接子元素
  while (targetNode && targetNode.parentElement !== editableRoot) {
    targetNode = targetNode.parentElement;
    // 遍历到body仍未找到则说明选区不在目标容器内,直接退出
    if (targetNode === document.body) return;
  }
  if (targetNode) {
    $(targetNode).addClass('indent');
  }
});

CSS代码

.indent{margin-left:30px;}

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable>
  <div>lorem</div>
  <div>ipsum</div>
  <div>dolor</div>
</div>
<button>CLICK</button>

使用时将光标定位在contenteditable内的任意一行,点击按钮即可为当前行添加30px的左侧缩进。

内容的提问来源于stack exchange,提问作者qadenza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:39:01