选中contenteditable文本时同步显示embed-block的选中状态
问题与解决方案
需求
在contenteditable容器内的embed-block块,需实现:
- 当文本与该块一同被选中时,块显示选中状态
- 禁止选中
embed-block内部的文本内容
问题根源
原代码中给embed-block设置了user-select: none,这会让浏览器完全忽略该元素的选中状态,导致选中范围包含它时,块不会显示任何选中样式。
解决方法
关键调整
- 移除
user-select: none,让embed-block能被浏览器识别为选中范围的一部分 - 保留内部元素的
contenteditable="false",确保内部内容不可编辑 - 通过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">  <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>  </span> ..... Following properties effects. user-select, draggble="true" </div>
效果验证
- 选中包含
embed-block的文本范围时,块会显示蓝色背景的选中样式,符合预期 - 内部内容无法被选中或编辑,满足需求
内容的提问来源于stack exchange,提问作者Vinod Gubbala
相关产品推荐
相关产品推荐

