js实现高亮
实现高亮的方法
使用CSS类切换 通过动态添加或移除CSS类来实现高亮效果。定义一个高亮样式类,在需要高亮时将其添加到元素上。
// CSS
.highlight {
background-color: yellow;
font-weight: bold;
}
// JavaScript
function toggleHighlight(element) {
element.classList.toggle('highlight');
}
// 使用示例
const targetElement = document.getElementById('target');
toggleHighlight(targetElement);
使用style属性直接修改 直接操作元素的style属性来改变外观,适合简单的高亮需求。
function highlightElement(element) {
element.style.backgroundColor = 'yellow';
element.style.fontWeight = 'bold';
}
function removeHighlight(element) {
element.style.backgroundColor = '';
element.style.fontWeight = '';
}
文本内容高亮
使用正则表达式替换 在文本内容中搜索关键词并包裹高亮标签,适用于大段文本的高亮处理。
function highlightText(text, keyword) {
const regex = new RegExp(keyword, 'gi');
return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}
// 使用示例
const originalText = 'This is a sample text with keywords.';
const keyword = 'sample';
const highlightedText = highlightText(originalText, keyword);
document.getElementById('content').innerHTML = highlightedText;
动态搜索高亮
实时输入搜索高亮 结合输入事件实现实时搜索和高亮显示。
const searchInput = document.getElementById('search');
const content = document.getElementById('content');
searchInput.addEventListener('input', () => {
const searchTerm = searchInput.value.trim();
if (searchTerm) {
const text = content.textContent;
const highlighted = highlightText(text, searchTerm);
content.innerHTML = highlighted;
} else {
content.innerHTML = content.textContent;
}
});
持久高亮效果
使用自定义属性存储状态 通过data属性保存高亮状态,便于后续操作。
function togglePersistentHighlight(element) {
const isHighlighted = element.dataset.highlighted === 'true';
if (isHighlighted) {
element.style.backgroundColor = '';
element.dataset.highlighted = 'false';
} else {
element.style.backgroundColor = 'yellow';
element.dataset.highlighted = 'true';
}
}
性能优化建议
使用DocumentFragment 批量操作DOM时使用DocumentFragment减少重绘。
function highlightMultiple(elements) {
const fragment = document.createDocumentFragment();
elements.forEach(el => {
const clone = el.cloneNode(true);
clone.classList.add('highlight');
fragment.appendChild(clone);
});
document.body.appendChild(fragment);
}
节流输入事件 对高频触发的事件进行节流处理。

function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
return func.apply(this, args);
};
}
searchInput.addEventListener('input', throttle(handleSearch, 300));






