Highlighting Text with JavaScript: A One-Time Spotlight
When it comes to highlighting text in a web page, we often resort to default browser functionality. However, what if you need a precise and one-time highlighting effect? Here's how you can achieve it using JavaScript.
The jQuery highlight effect provides a straightforward solution for text highlighting. But if you're seeking a raw JavaScript approach, consider the following code snippet:
function highlight(text) { const inputText = document.getElementById("inputText"); const innerHTML = inputText.innerHTML; const index = innerHTML.indexOf(text); if (index >= 0) { innerHTML = innerHTML.substring(0, index) + `<span class='highlight'>` + innerHTML.substring(index, index + text.length) + `</span>` + innerHTML.substring(index + text.length); inputText.innerHTML = innerHTML; } }
To match our highlighting effect with the text we want to highlight, we apply some CSS rules:
.highlight { background-color: yellow; }
Now, let's put it all together. We create an HTML element with the ID "inputText" where we want the highlighting to take place. We also add a button with the onclick event that triggers the "highlight" function.
<button onclick="highlight('fox')">Highlight</button> <div>
By clicking the "Highlight" button, the JavaScript code locates the first occurrence of "fox" in the text and encloses it within a element with the class "highlight." This span element applies the yellow background color, making the "fox" text stand out. This code sample provides a simple yet effective method for highlighting text in a web page. You can customize the search text, highlight color, or even extend the functionality to highlight multiple occurrences if needed. The above is the detailed content of How Can I Create a One-Time Text Highlighting Effect with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!