在頁面中高亮關鍵字時,必須避開 HTML 標籤,否則會破壞 DOM 結構(如將 <div> 中的 "div" 高亮導致標籤破損)。解決策略:暫存標籤、替換關鍵字、還原標籤。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>關鍵字高亮示範</title>
</head>
<body>
<div class="result" id="textbox">
<p>百度(Nasdaq簡稱:BIDU)是全球最大的中文搜索引擎,2000年1月由李彥宏、徐勇兩人創立於北京中關村,致力於向人們提供「簡單,可依賴」的</p>
<p>信息獲取方式。「百度」二字源於中國宋朝詞人辛棄疾的《青玉案·元夕》詞句「眾裡尋他千百度」,象征著百度對中文信息檢索技術的執著追求。</p>
</div>
<script>
function highlight(containerId, keyword) {
var container = document.getElementById(containerId);
if (!keyword) return;
// 1. 取得原始 HTML
var html = container.innerHTML;
// 2. 暫存所有 HTML 標籤,用佔位符替換
var tagRegex = /<[^>]+>/g;
var tags = [];
html = html.replace(tagRegex, function(match) {
tags.push(match);
return "{[(" + (tags.length - 1) + ")]}"; // 唯一佔位符
});
// 3. 分割關鍵字 (支援逗號、空白分隔)
var words = decodeURIComponent(keyword.replace(/,/g, ' ')).split(/\s+/);
// 4. 逐一替換關鍵字 (保留特殊字元)
words.forEach(function(word) {
if (!word) return;
// 轉義正則特殊字元
var escaped = word.replace(/[(){}.+*?^$|\[\]\\]/g, "\\$&");
var regex = new RegExp("(" + escaped + ")", "ig");
html = html.replace(regex, "<mark style='background:#ff0; color:#000;'>$1</mark>");
});
// 5. 還原 HTML 標籤
tags.forEach(function(tag, i) {
html = html.replace("{[(" + i + ")]}", tag);
});
// 6. 寫回容器
container.innerHTML = html;
}
// 執行高亮:關鍵字 "百度,李彥宏"
highlight("textbox", "百度,李彥宏");
</script>
</body>
</html>
/<[^>]+>/g 匹配所有標籤,替換為唯一佔位符 {[(index)]}。decodeURIComponent 處理 URL 編碼。word.replace(/[(){}.+*?^$|\[\]\\]/g, "\\$&") 防止關鍵字含特殊字元破壞正則。/ig 旗標。TreeWalker 遍歷文字節點直接包裹,避免 innerHTML 重繪整棵樹。setTimeout 300ms 防抖。function highlightWalk(containerId, keywords) {
var container = document.getElementById(containerId);
var walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT, null, false);
var node, text, regex = new RegExp(keywords.map(function(w) {
return w.replace(/[(){}.+*?^$|\[\]\\]/g, "\\$&");
}).join("|"), "gi");
while (node = walker.nextNode()) {
if (regex.test(node.nodeValue)) {
var span = document.createElement("span");
span.innerHTML = node.nodeValue.replace(regex, "<mark>$1</mark>");
node.parentNode.replaceChild(span, node);
}
}
}