How to highlight text using javascript

后端 未结 13 2238
名媛妹妹
名媛妹妹 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 02:57

    I was wondering that too, you could try what I learned on this post.

    I used:

    function highlightSelection() {
    			var userSelection = window.getSelection();
    			for(var i = 0; i < userSelection.rangeCount; i++) {
    				highlightRange(userSelection.getRangeAt(i));
    			}
    			
    		}
    			
    			function highlightRange(range) {
    			    var newNode = document.createElement("span");
    			    newNode.setAttribute(
    			       "style",
    			       "background-color: yellow; display: inline;"
    			    );
    			    range.surroundContents(newNode);
    			}
    
    	
    
    		
    			
    		
    		

    this is text, select and right click to high light me! if you can`t see the option, please use this

    you could also try it here: http://henriquedonati.com/projects/Extension/extension.html

    xc

提交回复
热议问题