【发布时间】:2023-01-24 04:18:43
【问题描述】:
我遇到了突出显示段落中选定文本的问题。具体来说,当用户删除选定的突出显示时,该段落有时会重新呈现,有时如果/当用户尝试创建新的突出显示时它不会引起问题。
这是场景:
这段落
<p>Over the last few weeks you have learned how a philosophical commitment to naturalism has led the scientific community to disallow the possibility of a supernatural explanation of the origin of our universe and the origin of life. You have also seen that this commitment is not based on scientifically observed data, and in fact, conveniently throws aside the very methodology that modern science claims to be built upon. The battle between modern science and the Bible is a battle of worldviews. It is not an argument about the facts that can be observed, but the explanations offered to account for them.</p>
用户突出显示一个选择: ...了解 philo 如何社交通讯意...
用户删除突出显示: ...了解如何对...做出哲学承诺
现在,如果用户再次尝试突出显示/取消突出显示这些单词的某些或部分,它会从 DOM 中删除文本。
我试图在删除选择后强制 DOM 刷新。
这是我的选择方法:
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)
}
【问题讨论】:
标签: javascript vue.js dom syntax-highlighting