Home > Article > Web Front-end > How to implement text highlighting in jQuery?
jQuery is a popular JavaScript library used to simplify the manipulation and event handling of HTML documents. When implementing the text highlighting function, you can use jQuery through the following steps:
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<input type="text" id="searchInput" placeholder="输入需要高亮显示的文本"> <button id="highlightBtn">高亮显示</button> <div id="content"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vehicula metus ac odio. </div>
$(document).ready(function() { $("#highlightBtn").click(function() { var searchString = $("#searchInput").val(); var content = $("#content").text(); var highlightedContent = content.replace(new RegExp(searchString, 'gi'), function(match) { return '<span class="highlighted">' + match + '</span>'; }); $("#content").html(highlightedContent); }); });
In the above code, first get the search text in the input box and the text in the content area. Then use JavaScript's replace method combined with regular expressions to add a tag to the matched text to achieve highlighting. Finally, the processed content is reset to the content area.
.highlighted { background-color: yellow; font-weight: bold; }
Through the above steps, you can realize the text highlighting function on the page. After the user enters the text that needs to be highlighted, click the button to highlight the matching text content. The power and convenience of jQuery make it easy and efficient to implement text highlighting.
The above is the detailed content of How to implement text highlighting in jQuery?. For more information, please follow other related articles on the PHP Chinese website!