萬盛學電腦網

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

jQuery 關鍵字高亮插件實現:支援中文、多詞、HTML 安全過濾

功能需求

  • 頁面內指定容器中,將搜尋關鍵字(支援多詞、中文)高亮顯示。
  • 不破壞原有 HTML 結構(不高亮標籤屬性值、標籤名)。
  • 可自定義高亮樣式類名、大小寫敏感度、清除上次高亮。

核心難點

  1. 避開 HTML 標籤:正則需區分「標籤內文字」與「標籤本身」。
  2. 中文 Unicode 處理:正則需正確匹配 Unicode 字元。
  3. 巢狀元素處理:遞歸遍歷文字節點而非直接 innerHTML 替換,避免事件綁定丟失、表單重置。

健壯實作:遍歷文字節點(推薦)

(function ($) {
  $.fn.highlight = function (keywords, options) {
    const opts = $.extend({
      className: 'highlight',
      caseSensitive: false,
      wordsOnly: false,     // 全詞匹配
      clearPrevious: true
    }, options);

    const $container = this;
    if (opts.clearPrevious) {
      $container.find('.' + opts.className).each(function () {
        this.parentNode.replaceChild(document.createTextNode(this.textContent), this);
      });
    }

    if (!keywords) return $container;

    const kwArray = Array.isArray(keywords) ? keywords : [keywords];
    const regexFlags = opts.caseSensitive ? 'g' : 'gi';

    // 遞歸處理文字節點
    function processNode(node) {
      if (node.nodeType === Node.TEXT_NODE) {
        let text = node.nodeValue;
        let matched = false;
        kwArray.forEach(kw => {
          const escaped = kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
          const pattern = opts.wordsOnly ? '\\b' + escaped + '\\b' : escaped;
          const regex = new RegExp(pattern, regexFlags);
          if (regex.test(text)) {
            matched = true;
            text = text.replace(regex, match => `${match}`);
          }
        });
        if (matched) {
          const wrapper = document.createElement('span');
          wrapper.innerHTML = text;
          node.parentNode.replaceChild(wrapper, node);
          // 扁平化:將 wrapper 子節點提升
          while (wrapper.firstChild) wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
          wrapper.parentNode.removeChild(wrapper);
        }
      } else if (node.nodeType === Node.ELEMENT_NODE) {
        // 跳過 script/style/textarea 等
        if (!/^(script|style|textarea|input|select|option)$/i.test(node.tagName)) {
          [...node.childNodes].forEach(processNode); // 複製陣列避免動態修改影響迭代
        }
      }
    }

    this.each(function () { processNode(this); });
    return $container;
  };
})(jQuery);

使用範例

<div id="content">
  <p>JavaScript 是一種直譯式程式語言。</p>
  <p>它廣泛用於 Web 開發。</p>
</div>

<script>
$('#content').highlight(['JavaScript', 'Web', '開發'], {
  className: 'kw-highlight',
  caseSensitive: false
});
</script>

<style>
.kw-highlight { background: #fff3cd; padding: 0 2px; border-radius: 2px; }
</style>

簡易版(innerHTML 替換,適用於靜態內容)

$.fn.simpleHighlight = function (query, className = 'highlight') {
  if (!query) return this;
  const regex = new RegExp('(<[^>]*>)|(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
  return this.each(function () {
    this.innerHTML = this.innerHTML.replace(regex, (m, tag, text) => tag ? tag : `${text}`);
  });
};

缺點:會破壞現有事件綁定、表單狀態、輸入框內容;不支援巢狀高亮。

進階功能擴展

  • 關鍵字統計:回傳 { highlightedCount: 12, keywordCounts: { 'JavaScript': 3, 'Web': 2 } }。
  • 滾動定位:高亮後自動滾動至第一個匹配處 document.querySelector('.highlight').scrollIntoView()。
  • 撤銷高亮:提供 .unhighlight() 方法還原文字節點。
  • 效能優化:大文檔使用 TreeWalker 遍歷文字節點,配合 requestIdleCallback 分批處理。
copyright © 萬盛學電腦網 all rights reserved