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

跨多标签选中文本包裹后选区重置问题的解决方法

解决range.surroundContents跨标签选区失效及选区重置问题

range.surroundContents用法简单,但选区跨越多个标签时会失效。比如有如下文本(方括号内为选区,不含方括号):

This [is a <strong>simple]</strong> test

要将该选区设置为斜体,预期结果应为:

This <em>is a </em><strong><em>simple</em></strong> test

我尝试修改startContainer和endContainer的内容后替换,结果文本选区被重置到startContainer的首尾位置,请问该如何避免这个问题?可以用下面的代码片段测试:选择从strong标签外部开始到标签内部结束的文本。


测试代码

JavaScript

document.getElementById('get').addEventListener('mousedown', e => {
  e.preventDefault();
   
  const selection = window.getSelection(),
    activeRange = selection.getRangeAt(0);
    
  alert(activeRange.startContainer.textContent);
  alert(activeRange.endContainer.textContent);
});

document.getElementById('replace').addEventListener('mousedown', e => {
  e.preventDefault();
  
  const selection = window.getSelection(),
    activeRange = selection.getRangeAt(0);
    
  let startHTML = activeRange.startContainer.textContent,
    endHTML = activeRange.endContainer.textContent;
  startHTML = startHTML.slice(0, activeRange.startOffset)+'['+startHTML.slice(activeRange.startOffset);
  endHTML = endHTML.slice(0, activeRange.endOffset)+']'+endHTML.slice(activeRange.endOffset);
  activeRange.startContainer.replaceWith(activeRange.createContextualFragment(startHTML));  
  activeRange.endContainer.replaceWith(activeRange.createContextualFragment(endHTML));
});

CSS

span{
  padding: 0.5rem 1rem;
  background: #CCC;
}

HTML

<p>This is a <strong>simple</strong> test</p>
<br>
<span id="get">Get selection</span>
<span id="replace">Replace Selection</span>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:52:01