Javascript selected text highlighting prob

后端 未结 6 604
名媛妹妹
名媛妹妹 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:43

    This solution is bit tricky, but I find it would be sufficient

    When you will see closely in selection object that we get through calling

    window.getSelection().getRangeAt(0)
    

    You will se that there are 4 properties: startContainer, startOffset, endContainer, endOffset.

    So now you need to start with startContainer with startOffset and start putting your necessary span nodes from there.

    If now it endContainer is different node then you need to start traversing nodes from startContainer to endContainer

    For traversing you need to check for child nodes and sibling nodes which you can get from DOM objects. So first go through startContainer, go through all its child and check if child node is inline element then apply span tag around it, and then you need to write few coding for various corner cases.

提交回复
热议问题