萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 關鍵字高亮顯示:多關鍵字、效能優化、避開標籤完整解決方案

核心需求

在靜態文章頁面中,動態高亮顯示指定關鍵字(如「美容、生活、購物」),關鍵字可隨時更新,不修改 HTML 來源。

方案演進

階段 1:簡單 replace(有缺陷)

// 缺點:會破壞 HTML 標籤屬性,如  變成 
txt.innerHTML = txt.innerHTML.replace(/關鍵字/gi, "<font color=red>關鍵字</font>");

階段 2:多關鍵字替換(仍破壞標籤)

txt.innerHTML = txt.innerHTML.replace(/(美容)|(生活)|(購物)/gi, "<font color=red>$1$2$3</font>");

階段 3:TextRange 純文字處理(IE 專用,已淘汰)

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('美容|生活|購物');

現代最佳實踐:TreeWalker 遍歷文字節點

優點:不破壞 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' });
});

CSS 樣式

.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全嚴重快❌
TextRangeIE only否中❌ 已淘汰
TreeWalker + Fragment現代瀏覽器否優✅ 最佳
copyright © 萬盛學電腦網 all rights reserved