在靜態文章頁面中,動態高亮顯示指定關鍵字(如「美容、生活、購物」),關鍵字可隨時更新,不修改 HTML 來源。
// 缺點:會破壞 HTML 標籤屬性,如 變成
txt.innerHTML = txt.innerHTML.replace(/關鍵字/gi, "<font color=red>關鍵字</font>");
txt.innerHTML = txt.innerHTML.replace(/(美容)|(生活)|(購物)/gi, "<font color=red>$1$2$3</font>");
function highlight(key) {
var keys = key.split('|');
for (var i = 0; i < keys.length; i++) {
var rng = document.body.createTextRange();
while (rng.findText(keys[i])) {
rng.pasteHTML(rng.text.fontcolor('red'));
}
}
}
highlight('美容|生活|購物');
優點:不破壞 DOM 結構、不觸發重排、支援所有現代瀏覽器、可精確跳過 script/style/textarea 等標籤。
function highlightKeywords(container, keywords, options = {}) {
const {
className = 'highlight',
tagName = 'mark',
caseSensitive = false,
wholeWord = false
} = options;
if (!container || !keywords?.length) return;
// 建立正則:排除已高亮區塊、支援全字匹配
const escaped = keywords.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
let pattern = escaped.join('|');
if (wholeWord) pattern = '\\b(' + pattern + ')\\b';
const regex = new RegExp(pattern, caseSensitive ? 'g' : 'gi');
// TreeWalker 只遍歷文字節點
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_TEXT,
{
acceptNode: node => {
// 跳過 script/style/textarea/option 內容
const parent = node.parentElement;
if (!parent) return NodeFilter.FILTER_REJECT;
const tag = parent.tagName.toLowerCase();
if (['script', 'style', 'textarea', 'select', 'option'].includes(tag))
return NodeFilter.FILTER_REJECT;
// 跳過已高亮元素內部
if (parent.closest(`.${className}`))
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
}
},
false
);
const textNodes = [];
while (walker.nextNode()) textNodes.push(walker.currentNode);
textNodes.forEach(node => {
const text = node.textContent;
if (!regex.test(text)) return;
const frag = document.createDocumentFragment();
let lastIndex = 0;
let match;
regex.lastIndex = 0; // 重置全域正則
while ((match = regex.exec(text)) !== null) {
// 非匹配部分
if (match.index > lastIndex) {
frag.appendChild(document.createTextNode(text.slice(lastIndex, match.index)));
}
// 匹配部分包裝
const mark = document.createElement(tagName);
mark.className = className;
mark.textContent = match[0];
frag.appendChild(mark);
lastIndex = match.index + match[0].length;
}
// 剩餘文字
if (lastIndex < text.length) {
frag.appendChild(document.createTextNode(text.slice(lastIndex)));
}
node.parentNode.replaceChild(frag, node);
});
}
// 使用範例
document.addEventListener('DOMContentLoaded', () => {
const article = document.getElementById('article-content');
const keywords = ['美容', '生活', '購物', '文章', '關鍵字', '功能'];
highlightKeywords(article, keywords, { className: 'kw-highlight' });
});
.kw-highlight {
background: #fff3cd;
color: #856404;
padding: 0 2px;
border-radius: 3px;
font-weight: 500;
}
| 優化點 | 說明 |
|---|---|
| TreeWalker | 只遍歷文字節點,避開 DOM 樹操作 |
| DocumentFragment | 批次建立節點,單次 replaceChild |
| 跳過已高亮區塊 | 防止巢狀高亮、無限迴圈 |
| 排除標籤 | 不處理 script/style/表單元素內容 |
| 重置 regex.lastIndex | 全域正則在迴圈中必須手動重置 |
// 移除舊高亮
function removeHighlights(container, className = 'highlight') {
container.querySelectorAll(`.${className}`).forEach(el => {
el.outerHTML = el.textContent; // 還原純文字
});
}
// 更新關鍵字
function updateKeywords(newKeywords) {
removeHighlights(document.getElementById('article-content'));
highlightKeywords(document.getElementById('article-content'), newKeywords);
}
// 範例:從 API 取得關鍵字
fetch('/api/keywords').then(r => r.json()).then(data => updateKeywords(data.keywords));
| 方法 | 相容性 | 破壞 HTML | 效能 | 推薦度 |
|---|---|---|---|---|
| innerHTML replace | 全 | 嚴重 | 快 | ❌ |
| TextRange | IE only | 否 | 中 | ❌ 已淘汰 |
| TreeWalker + Fragment | 現代瀏覽器 | 否 | 優 | ✅ 最佳 |