简体   繁体   中英

How browser highlight text without adding any tags around word

Can anyone help me that how the browser highlight text (when we use ctrl+f and search any word) without dom manipulation or with adding any tag around the word. I have to implement search functionality on my application, where i have online book creator and its preview. User can find any word with search button and i am showing list of that found word. Where user click on any item in list i have to send user to particular portion of word. After that i am showing that word with highlighted background (which is hide after 1 second). But when i add span tag with highlight class and remove it, the lines in books are moving in some cases if the word found at the end of line.

<span class="highlight">The word founded by search</span>

Then i see the browser's search functionality, i can see browser din't add any tag to highlight text. May be because of its doing by canvas. Can anybody help me about the problem, can i highlight text without adding any tag or class or how the browser exactly do this.

Create the text for test purposes:

 function myFunction() { //This function is for test purposes document.open(); var data = document.write("hih This part is for test purposes uihuiuuh hhhiuh hhihi Hello World gukhjggkhgkghkghkgkkg hvbhjj bjhbjhhjhbgjhb jkjkjhjkh hkjhkjh jhjkhkj jhjkhkj jhkj kjhjkhk hjkhkjhjkh jjjjkjhiooigsesres lllljlk kjlj hgfgfhgfghfgfhgfgfhgfytfytftfytfytffftfftyftftyfdrdres hihhhggyg gvghggfhgf jjgygjyg hjgjhgjhg hhjgg hbhjb"); document.close(); $("#dvContent").html(data); } 
 <p>Click the button to open an output stream, add some text, and close the output stream.</p> <button onclick="myFunction()">Try it</button> <div id = "dvContent"> </div> 

If you want to open an external document

Jscript:

    $(document).ready(function() {
        $("#lesen").click(function() {
            $.ajax({
                url : "helloworld.txt",
                dataType: "text",
                success : function (data) {
                    $("#dvContent").html(data);
                }
            });
        });

}); 

html:

<div id = "dvContent" >
</div>

Creat your key press trigger exemple from Get a list of all currently pressed keys in Javascript

 var keys = []; document.body.innerHTML = "Keys currently pressed: " window.addEventListener("keydown", function(e){ keys[e.keyCode] = e.keyCode; var keysArray = getNumberArray(keys); document.body.innerHTML = "Keys currently pressed:" + keysArray; if(keysArray.toString() == "17,65"){ document.body.innerHTML += " Select all!" } }, false); window.addEventListener('keyup', function(e){ keys[e.keyCode] = false; document.body.innerHTML = "Keys currently pressed: " + getNumberArray(keys); }, false); function getNumberArray(arr){ var newArr = new Array(); for(var i = 0; i < arr.length; i++){ if(typeof arr[i] == "number"){ newArr[newArr.length] = arr[i]; } } return newArr; } 

Manipulate the trigger to make a textbox appear to enter the text or word that we are looking for.

 var keys = []; window.addEventListener("keydown", function(e){ keys[e.keyCode] = e.keyCode; var keysArray =keysArray = getNumberArray(keys); document.body.innerHTML = "Keys currently pressed:" + keysArray; if(keysArray.toString() == "17,65"){ var str_comp = prompt("Text to find", ""); keys = []; document.body.innerHTML = ""; document.body.innerHTML = str_comp; } }, false); window.addEventListener('keyup', function(e){ keys[e.keyCode] = false; document.body.innerHTML = getNumberArray(keys); }, false); function getNumberArray(arr){ var newArr = new Array(); for(var i = 0; i < arr.length; i++){ if(typeof arr[i] == "number"){ newArr[newArr.length] = arr[i]; } } return newArr; } 
 

A Simple find text script http://www.jquerybyexample.net/2012/03/how-to-underline-particular-word-using.html Provided by @T.Shah

 $(document).ready(function(){ var dvWords = $("#dvContent").html().split(' '); var dvHTML = '' for (i = 0; i < dvWords.length; i++) { if (dvWords[i].toLowerCase() == 'jquery') { dvHTML += ' ' + '<span>' + dvWords[i] + '</span>'; } else { dvHTML += ' ' + dvWords[i]; } } $("#dvContent").html(dvHTML); }); 
 body { font-family:Arial; font-size : 10pt; } #dvContent span { text-decoration: underline; font-weight : bold; color : Blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="dvContent"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. jQuery In nulla est, congue quis sagittis vel, ullamcorper euismod mi. Duis gravida, nibh id placerat sagittis, quam tellus vestibulum nisl, a feugiat augue ipsum sit amet urna. Sed semper urna non odio bibendum blandit. Etiam eu jQuery orci ut arcu commodo dignissim. Curabitur sit amet massa velit. Fusce in felis ac ipsum ultrices elementum. Suspendisse potenti.Lorem ipsum dolor sit amet, consectetur jQuery adipiscing elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nulla facilisi. Suspendisse turpis nulla, mattis et scelerisque vitae, eleifend dictum nibh. Suspendisse at felis velit, sed sollicitudin enim. Aliquam erat volutpat. jQuery Quisque sed purus ac enim volutpat iaculis eget et risus. Donec consequat odio vel sem dignissim eu venenatis nisl vehicula. Suspendisse potenti. Maecenas et arcu et quam dapibus lobortis. Curabitur tincidunt tincidunt dictum. jQuery Sed porta cursus jQuery sodales. Cras sodales, ipsum non molestie malesuada, erat lacus faucibus orci, id venenatis leo nibh quis purus. Proin eu sem vitae felis pellentesque suscipit vitae id erat. In eros mi, egestas non cursus ac, bibendum ac nisl. Cras convallis elit jQuery in felis congue ut consectetur ipsum egestas. Pellentesque jQuery felis elit, posuere ut aliquet id, fermentum et purus. Quisque ac nunc vitae sapien eleifend sollicitudin. Proin nisl est, congue et adipiscing nec, rutrum non eros. Sed ultrices ullamcorper justo, in lobortis quam mollis ac. Proin ac lacinia eros. Integer jQuery suscipit consectetur scelerisque. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean sem sapien, sollicitudin sed sodales non, cursus nec ipsum. Aenean pretium eros non felis accumsan vitae tristique quam dapibus. Donec eget quam sed sem varius rutrum eget nec mi. jQuery Cras ut ipsum nisl. </div> 

To conclude, let's put it all together

 var keys = []; var data = myFunction(); $("#dvContent").html(data); window.addEventListener("keydown", function(e){ keys[e.keyCode] = e.keyCode; var keysArray =keysArray = getNumberArray(keys); if(keysArray.toString() == "65,68"){ var str_comp = prompt("Text to find", ""); get_str_eql(str_comp, data); keys = []; } }, false); window.addEventListener('keyup', function(e){ keys[e.keyCode] = false; getNumberArray(keys); }, false); function getNumberArray(arr){ var newArr = new Array(); for(var i = 0; i < arr.length; i++){ if(typeof arr[i] == "number"){ newArr[newArr.length] = arr[i]; } } return newArr; } function myFunction() { //This function is for test purposes var data = "hih This part is for test purposes uihuiuuh hhhiuh hhihi Hello World gukhjggkhgkghkghkgkkg hvbhjj bjhbjhhjhbgjhb ola jkjkjhjkh hkjhkjh jhjkhkj jhjkhkj jhkj kjhjkhk hjkhkjhjkh jjjjkjhiooigsesres ola lllljlk kjlj hgfgfhgfghfgfhgfgfhgfytfytftfytfytffftfftyftftyfdrdres hihhhggyg gvghggfhgf jjgygjyg hjgjhgjhg hhjgg hbhjb ola"; return data; } function get_str_eql(string_val, data_val){ var dvWords = data_val.split(" "); var dvHTML = ""; for (i = 0; i < dvWords.length; i++) { if (dvWords[i] == string_val) { dvHTML += " " + "<span>" + dvWords[i] + "</span>"; } else { dvHTML += " " + dvWords[i]; } } $("#dvContent").html(dvHTML); } 
 body { font-family:Arial; font-size : 10pt; } #dvContent span { text-decoration: underline; font-weight : bold; color : Red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id = "dvContent"> </div> <br> </br> <p>Click in the keys 'a' and 'd' to make the search.</p> 

It's working. Now it's just a little more work, and you have a word search system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM