可以通过以下步骤实现:
<!DOCTYPE html>
<html>
<head>
<title>Highlight Words</title>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<p id="text">This is a sample text for highlighting words.</p>
<script src="highlight.js"></script>
</body>
</html>
document.addEventListener("DOMContentLoaded", function(event) {
var textElement = document.getElementById("text");
var text = textElement.innerHTML;
var wordsToHighlight = ["sample", "highlighting"];
wordsToHighlight.forEach(function(word) {
var regex = new RegExp(word, "gi");
text = text.replace(regex, "<span class='highlight'>$&</span>");
});
textElement.innerHTML = text;
});
这段JavaScript代码首先获取包含文本的元素,然后使用正则表达式替换所有要突出显示的单词为带有highlight类的span元素。
完成上述步骤后,打开HTML文件,页面上的"sample"和"highlighting"单词将会以黄色背景突出显示。
这种技术适用于在Web应用程序中高亮显示关键词、搜索结果、拼写检查等功能。
领取专属 10元无门槛券
手把手带您无忧上云