How to highlight text using javascript

后端 未结 13 2234
名媛妹妹
名媛妹妹 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:00

    Using the surroundContents() method on the Range type. Its only argument is an element which will wrap that Range.

    function styleSelected() {
      bg = document.createElement("span");
      bg.style.backgroundColor = "yellow";
      window.getSelection().getRangeAt(0).surroundContents(bg);
    }
    

提交回复
热议问题