js实现高亮
实现文本高亮的几种方法
使用HTML和CSS结合JavaScript
通过JavaScript动态添加HTML标签和CSS类来实现高亮效果。以下是一个基本示例:
function highlightText(text, searchTerm) {
const regex = new RegExp(searchTerm, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
// 使用示例
const originalText = "这是一个测试文本,测试高亮功能";
const highlightedText = highlightText(originalText, "测试");
document.body.innerHTML = highlightedText;
对应的CSS样式:
.highlight {
background-color: yellow;
color: black;
}
使用Range和Selection API
这种方法适合对DOM中的特定部分进行高亮,而不需要替换整个HTML内容:

function highlightSelection() {
const selection = window.getSelection();
if (selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.className = 'highlight';
range.surroundContents(span);
}
}
使用第三方库
Mark.js是一个专门用于文本高亮的轻量级库:
// 引入Mark.js后
const instance = new Mark(document.querySelector("body"));
instance.mark("需要高亮的词", {
className: 'highlight',
separateWordSearch: false
});
动态高亮搜索关键词
实现实时搜索高亮功能:

const searchInput = document.getElementById('search');
searchInput.addEventListener('input', (e) => {
const searchTerm = e.target.value;
const textNodes = document.querySelectorAll('.content');
textNodes.forEach(node => {
const text = node.textContent;
const highlighted = highlightText(text, searchTerm);
node.innerHTML = highlighted;
});
});
高亮性能优化
对于大量文本的高亮操作,考虑以下优化:
function highlightOptimized(text, words) {
const uniqueWords = [...new Set(words)];
const regex = new RegExp(uniqueWords.join('|'), 'gi');
return text.replace(regex, match => {
const color = getColorForWord(match);
return `<span style="background-color: ${color}">${match}</span>`;
});
}
清除高亮
在应用新高亮前清除旧高亮:
function removeHighlights() {
const highlights = document.querySelectorAll('.highlight');
highlights.forEach(hl => {
const parent = hl.parentNode;
parent.replaceChild(document.createTextNode(hl.textContent), hl);
parent.normalize();
});
}
以上方法可以根据具体需求选择使用,简单的文本替换适合大多数场景,而Range API更适合精确控制高亮位置。第三方库则提供了更多开箱即用的功能。






