Javascript selected text highlighting prob

后端 未结 6 612
名媛妹妹
名媛妹妹 2021-01-31 05:14

I have a html page with text content. On selecting any text and pressing the highlight button, I can change the style of the selected text to highlight the same. To implement th

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-31 05:40

    try this:

    newNode.appendChild(range.extractContents())
    

    according to MDN:

    Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.

    Whereas Range.surroundContents:

    An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.

    Didn't test, but...

提交回复
热议问题