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

选中contenteditable文本时同步显示embed-block的选中状态

问题与解决方案

需求

在contenteditable容器内的embed-block块,需实现:

  • 当文本与该块一同被选中时,块显示选中状态
  • 禁止选中embed-block内部的文本内容

问题根源

原代码中给embed-block设置了user-select: none,这会让浏览器完全忽略该元素的选中状态,导致选中范围包含它时,块不会显示任何选中样式。

解决方法

关键调整

  1. 移除user-select: none,让embed-block能被浏览器识别为选中范围的一部分
  2. 保留内部元素的contenteditable="false",确保内部内容不可编辑
  3. 通过CSS伪类给embed-block添加选中样式,同时屏蔽内部元素的选中效果

修改后的代码

CSS

[contenteditable="true"] {
  border: 1px solid gray;
  padding: 20px;
}
.embed-block {
  border: 1px solid green;
  display: inline-block;
  border-radius: 20px;
  padding: 5px;
}
/* 定义embed-block的选中样式 */
.embed-block::selection {
  background-color: #b4d5ff;
  border-radius: 20px;
}
.embed-block::-moz-selection {
  background-color: #b4d5ff;
  border-radius: 20px;
}
/* 屏蔽内部元素的选中效果 */
.embed-block [contenteditable="false"]::selection,
.embed-block [contenteditable="false"]::-moz-selection {
  background-color: transparent;
}

HTML

<div contenteditable="true">
  lorem ipsum
  <span class="embed-block" draggable="true" data-value="test">
      &#xFEFF;
      <span contenteditable="false">
         <div class="embed-block-child1">
           <div class="embed-block-child2">
              <div class="embed-block-child3">
                 <span style="margin-right:4px">some block</span>
              </div>
           </div>
         </div>
      </span>
      &#xFEFF;
  </span>

  .....
  Following properties effects. user-select, draggble="true"
</div>

效果验证

  • 选中包含embed-block的文本范围时,块会显示蓝色背景的选中样式,符合预期
  • 内部内容无法被选中或编辑,满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:20:24