How to highlight text using javascript

后端 未结 13 2233
名媛妹妹
名媛妹妹 2020-11-22 02:32

Can someone help me with a javascript function that can highlight text on a web page. And the requirement is to - highlight only once, not like highlight all occurrences of

相关标签:
13条回答
  • 2020-11-22 03:15
    function stylizeHighlightedString() {
    
        var text = window.getSelection();
    
        // For diagnostics
        var start = text.anchorOffset;
        var end = text.focusOffset - text.anchorOffset;
    
        range = window.getSelection().getRangeAt(0);
    
        var selectionContents = range.extractContents();
        var span = document.createElement("span");
    
        span.appendChild(selectionContents);
    
        span.style.backgroundColor = "yellow";
        span.style.color = "black";
    
        range.insertNode(span);
    }
    
    0 讨论(0)
提交回复
热议问题