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

移除文本高亮时保留window.getselection内HTML标签的问题

文本高亮移除功能的HTML标签误删问题

我开发了一段支持用户高亮文本的代码,高亮内容会保存到数据库,用户返回页面时高亮状态能保留。但移除高亮时遇到问题:如果选中的文本里包含HTML标签,这些标签会被误删。我希望只移除用于高亮的span标签,保留其他所有HTML标签。除了移除功能,其他部分都正常运行。

示例代码结构

<p id="SOMEID">Paragraph text <span class="highlight">Highlighted text <em>Some highlighted text</em> some more highlighted text </span> more paragraph text</p>

我的实现代码

surroundSelection(action) {
    var span = document.createElement("span")
    
    if(action == 'highlight')
        span.className = 'highlighted'

    var sel = window.getSelection()
    
    if(action == 'remove') {
        let ancestor = sel.anchorNode.parentNode.parentNode
        let parent = sel.anchorNode.parentElement
        
        ancestor.insertBefore(sel.anchorNode, parent)
        sel.anchorNode.remove()
    }
    if (window.getSelection()) {
        
        if (sel.rangeCount) {
            var range = this.selectedRange.cloneRange()
        
            if(action == 'highlight')
                range.surroundContents(span)

            sel.removeAllRanges()
            sel.addRange(range)
        }
    }
    this.saveHighlight(sel, action)
},

问题场景

  • 选择包含部分<em>标签的文本(例如:wasted. “Not that I seek the gift itself, but I seek for the profit which increases to your account” (Philippians),点击高亮弹窗后会触发后续问题。
  • 文本高亮后,选中高亮区域内的<em>标签部分内容时,仍显示高亮弹窗而非移除弹窗;选中“wasted”点击移除后,对应文本会丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:34:50