js实现高亮显示
高亮显示的实现方法
在JavaScript中实现高亮显示通常涉及文本内容的查找与样式修改。以下是几种常见方法:
使用CSS类与DOM操作
通过创建高亮样式类并动态应用到匹配文本节点:
function highlightText(text, searchTerm) {
const regex = new RegExp(searchTerm, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
// 使用示例
document.getElementById('content').innerHTML =
highlightText(document.getElementById('content').textContent, '关键词');
配套CSS样式:
.highlight {
background-color: yellow;
font-weight: bold;
}
使用Range和Selection API
适用于精确控制选中范围的高亮需求:
function highlightSelection() {
const selection = window.getSelection();
if (selection.toString().length > 0) {
const range = selection.getRangeAt(0);
const span = document.createElement('span');
span.className = 'highlight';
range.surroundContents(span);
}
}
使用第三方库
如Mark.js库提供更丰富的高亮功能:
// 引入mark.js后
const markInstance = new Mark(document.querySelector('.context'));
markInstance.mark('keyword', {
className: 'custom-highlight',
acrossElements: true
});
动态搜索高亮实现
结合输入框实时高亮匹配内容:
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', () => {
const term = searchInput.value.trim();
if (term) {
const instance = new Mark(document.querySelector('#content'));
instance.unmark().mark(term);
}
});
性能优化建议
对于大文本内容的高亮操作:
- 使用文档片段(DocumentFragment)进行批量DOM操作
- 采用防抖(debounce)技术控制高频触发
- 优先使用textContent而非innerHTML
- 考虑虚拟滚动技术处理超长文本
注意事项
- 处理HTML转义防止XSS攻击
- 清除旧高亮时注意内存泄漏问题
- 跨元素匹配时需要特殊处理文本节点
- 考虑浏览器兼容性(尤其IE11及以下)
以上方法可根据具体场景选择使用,建议复杂需求优先考虑成熟的第三方库实现。






