js实现高亮显示
实现高亮显示的方法
在JavaScript中实现高亮显示通常涉及操作DOM元素,修改文本样式或添加特定类。以下是几种常见方法:
使用HTML和CSS结合JavaScript
通过JavaScript动态添加高亮样式类,CSS定义高亮效果:
.highlight {
background-color: yellow;
color: black;
}
function highlightText(elementId, textToHighlight) {
const element = document.getElementById(elementId);
const content = element.innerHTML;
const highlightedContent = content.replace(
new RegExp(textToHighlight, 'gi'),
match => `<span class="highlight">${match}</span>`
);
element.innerHTML = highlightedContent;
}
使用Range和Selection API
适用于精确控制选中文本范围的高亮:
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简化操作:
<script src="https://cdn.jsdelivr.net/npm/mark.js@8.11.1/dist/mark.min.js"></script>
const instance = new Mark(document.querySelector('.content'));
instance.mark('keyword', {
className: 'highlight'
});
注意事项
- 直接操作innerHTML可能导致XSS漏洞,需对输入内容转义
- 高亮大量文本时可能影响性能,建议使用文档片段(DocumentFragment)
- 清除旧高亮时需遍历移除相关DOM节点或类名
清除高亮的方法
function removeHighlights() {
const highlights = document.querySelectorAll('.highlight');
highlights.forEach(highlight => {
const parent = highlight.parentNode;
parent.replaceChild(document.createTextNode(highlight.textContent), highlight);
});
}






