【问题标题】:Rebuild DOM after a window.selection has been removed删除 window.selection 后重建 DOM
【发布时间】: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>

检查元素的 DOM

用户突出显示一个选择: ...了解 philo 如何社交通讯意...

高亮后的DOM

用户删除突出显示: ...了解如何对...做出哲学承诺

去掉高亮后的DOM

现在,如果用户再次尝试突出显示/取消突出显示这些单词的某些或部分,它会从 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


    【解决方案1】:

    我找到了解决办法。在 saveHighlight 方法中,我调用了一个新函数,该函数采用选择的 ID 和 innerHtml,然后我替换了 innerHtml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-30
      • 2011-01-02
      • 1970-01-01
      • 2014-03-21
      • 2017-05-08
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多