Home  >  Article  >  Web Front-end  >  How to implement text highlighting in jQuery?

How to implement text highlighting in jQuery?

WBOY
WBOYOriginal
2024-02-27 12:12:04922browse

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:

  1. Introduce the jQuery library file:
    First, you need to introduce the jQuery library file into the HTML file. You can Add to the page via CDN link or local file. Add the following code snippet in the tag:
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  1. Writing HTML structure:
    Add a text box or other HTML elements to the page for input that needs to be highlighted The text content displayed. The code example is as follows:
<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>
  1. Write jQuery code:
    Next, write code through jQuery to implement the text highlighting function. The code example is as follows:
$(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.

  1. CSS style setting:
    In order to make the highlighting effect better, you need to set the style of the highlighted text in the CSS file. The code example is as follows:
.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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn