js实现高亮显示
高亮显示的实现方法
使用CSS类切换
通过JavaScript动态添加或移除CSS类实现高亮效果。定义一个高亮样式类:
.highlight {
background-color: yellow;
font-weight: bold;
}
使用JavaScript切换类:
const element = document.getElementById('target');
element.classList.add('highlight');
// 取消高亮
element.classList.remove('highlight');
动态修改内联样式
直接修改元素的style属性实现高亮:

const element = document.getElementById('target');
element.style.backgroundColor = 'yellow';
element.style.fontWeight = 'bold';
// 恢复默认
element.style.backgroundColor = '';
element.style.fontWeight = '';
文本节点高亮处理
对于需要高亮文本片段的情况,可以使用Range和DocumentFragment:
function highlightText(text, element) {
const content = element.textContent;
const index = content.indexOf(text);
if (index >= 0) {
const range = document.createRange();
const span = document.createElement('span');
span.className = 'highlight';
range.setStart(element.firstChild, index);
range.setEnd(element.firstChild, index + text.length);
range.surroundContents(span);
}
}
使用第三方库
考虑使用专门的文本高亮库如Mark.js:

// 引入Mark.js后
const instance = new Mark(document.querySelector('body'));
instance.mark('keyword', {
className: 'highlight'
});
动画高亮效果
添加过渡动画增强视觉效果:
.highlight {
background-color: yellow;
transition: background-color 0.5s ease;
}
.highlight-fade {
background-color: transparent;
}
element.classList.add('highlight');
setTimeout(() => {
element.classList.replace('highlight', 'highlight-fade');
}, 1000);
高亮性能优化
对于大量元素的高亮操作,使用文档片段减少重绘:
const fragment = document.createDocumentFragment();
items.forEach(item => {
const clone = item.cloneNode(true);
clone.classList.add('highlight');
fragment.appendChild(clone);
});
container.appendChild(fragment);
事件驱动高亮
响应鼠标事件实现交互式高亮:
document.addEventListener('mouseover', (e) => {
if (e.target.matches('.highlightable')) {
e.target.classList.add('highlight');
}
});
document.addEventListener('mouseout', (e) => {
if (e.target.matches('.highlightable')) {
e.target.classList.remove('highlight');
}
});
每种方法适用于不同场景,CSS类切换适合简单交互,文本节点处理适合搜索高亮,第三方库适合复杂文本匹配,动画效果增强用户体验,性能优化处理大数据量情况。






