移除文本高亮时保留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
相关产品推荐
相关产品推荐

