Many times in the project development, the front-end search function text highlighting problem. Every time we encounter keywords across elements, because of the limited front-end knowledge, we can make do with regular, poor experience and high development difficulty.
——Today, I found that this plug-in has solved the problem perfectly.
JavaScript key highlights, perfect solution:
Search terms are highlighted for each use case. It can be used with pure JavaScript or jQuery plug-ins.
In some cases, even if the match appears in multiple elements, the match needs to be highlighted. Suppose you want to highlight the context of the search term "highlight text":
Sample DEMO:
<!DOCTYPE> <html> <head> <title>mark.js</title> <meta name="generator" content="editplus"/> <style type="text/css"> mark { background: orange; color: black; } </style> </head> <body> <input type="text" value="test"> <div id="context"> <p>Clear task: to build a moderately prosperous society in an all-round way</p> <p data-spm-anchor-id="0.0.0.i1">From the high slope of the loess to the boundless forest, from the snowy plateau to the grassland pastoral area, from the northwest border to the Yunnan Guizhou Plateau, Xi Jinping went to the poorest and most backward areas of China many times to observe the true feelings and see the real poverty. He once said<strong><span>"I'm worried about their difficulties in life. I'm happy with every bit of their life.</span></strong>. </p> <span>The Chinese people</span><b>the people</b><i>Republic</i> </div> <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.es6.js"></script> <script type="text/javascript"> $(function () { $("input").on("input.highlight", function () { // Determine specified search term var searchTerm = $(this).val(); // Highlight search term inside a specific context $("#context").unmark().mark(searchTerm, { "acrossElements": true, "separateWordSearch": false, } ); }).trigger("input.highlight").focus(); }); </script> </body> </html>
Original effect:
Search for "he said" they "effect:
Search "people of China" effect:
For specific use, please refer to the plug-in website:
https://markjs.io/