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

如何替代已废弃的execCommand实现JS选中文本后持续高亮?

实现方案

基于你现有的DOM结构,我们直接使用标准Selection和Range API替换废弃的execCommand即可实现需求,完整可运行代码如下:

完整代码

CSS部分

首先新增高亮样式,方便后续统一管理效果:

.highlight {
  background-color: red;
  /* 可按需扩展其他样式属性 */
}

HTML部分

和你原有结构保持一致即可:

<div class="reveal" id="textToSelect">
  <span class="reveal-text">texttexttexttexttexttext</span>
  <span class="reveal-text">texttexttexttexttexttexttexttexttexttexttexttext</span>
  <span class="reveal-text">texttexttexttexttexttext</span>
  <span class="reveal-text">texttexttexttexttexttexttexttext</span>
  <span class="reveal-text">Ctexttexttexttexttexttexttexttexttext</span>
  <span class="reveal-text">texttexttexttexttexttexttexttext</span>
</div>

JS部分

document.getElementById('textToSelect').addEventListener('mouseup', function() {
  const sel = window.getSelection();
  // 过滤无选中内容、选中内容为空的异常场景
  if (!sel.rangeCount || sel.isCollapsed) return;

  const range = sel.getRangeAt(0);
  // 校验选中范围是否在当前文本容器内,避免处理容器外的选中内容
  if (!this.contains(range.commonAncestorContainer)) return;

  // 创建自定义高亮节点
  const highlightSpan = document.createElement('span');
  highlightSpan.classList.add('highlight');

  try {
    // 选中范围在单个节点内时,直接用高亮节点包裹内容,性能最优
    range.surroundContents(highlightSpan);
  } catch (e) {
    // 处理跨多个节点选中的场景:先提取选中内容,再插入高亮节点
    const selectedContent = range.extractContents();
    highlightSpan.appendChild(selectedContent);
    range.insertNode(highlightSpan);
  }

  // 清除选中状态,高亮效果保留
  sel.removeAllRanges();
});

逻辑说明

  • 所有调用的API均为当前Web标准规范内的接口,无兼容性问题,完全替代废弃的execCommand能力
  • 兼顾单节点选中、跨节点选中两类场景,覆盖你现有结构下的所有选中交互
  • 高亮样式抽离为CSS类,后续调整颜色、样式无需修改JS逻辑,可维护性更高

内容的提问来源于stack exchange,提问作者Stéphan E

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:24:03