DIV CSS 佈局教程網

用 jQuery 做瀏覽器式搜尋:關鍵字高亮與上下跳轉
編輯:JQuery特效代碼     

把下面這段存成 .html 檔就能直接執行。它模擬了瀏覽器 Ctrl+F 的效果:輸入關鍵字後全文標記,並可用「上一個/下一個」在命中結果間跳著看。

<html>
<head>
  <style type="text/css">
    .res { color: Red; }
  </style>
  <script src="jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    var oldKey = "";
    var index = -1;
    var pos = new Array();
    var oldCount = 0;

    function search(flg) {
      if (!flg) {
        index++;
        index = index == oldCount ? 0 : index;
      } else {
        index--;
        index = index < 0 ? oldCount - 1 : index;
      }

      $(".result").removeClass("res");
      $("#toresult").remove();

      var key = $("#key").val(); // 取關鍵字
      if (!key) {
        oldKey = "";
        return; // 空字串直接退出
      }

      if (oldKey != key) {
        // 關鍵字變了,重新掃描
        index = 0;
        $(".result").each(function () {
          $(this).replaceWith($(this).html());
        });
        pos = new Array();

        $("body").html($("body").html().replace(
          new RegExp(key, "gm"),
          "<span id='result" + index + "' class='result'>" + key + "</span>"
        ));

        $("#key").val(key);
        oldKey = key;

        $(".result").each(function () {
          pos.push($(this).offset().top);
        });
        oldCount = $(".result").length;
      }

      $(".result:eq(" + index + ")").addClass("res");
      $("body").scrollTop(pos[index]);
    }
  </script>
</head>
<body>
  <div style="position: fixed; right: 20px; top: 0;">
    <input id="key" type="text" style="width: 100px;" />
    <input type="button" value="下一個" onclick="search()" />
    <input type="button" value="上一個" onclick="search(1)" />
  </div>
  <div style="height: 50px;"></div>
  <div style="height: 200px;">1 待搜索的文本。</div>
  <div style="height: 200px;">2 待搜索的文本。</div>
  <div style="height: 200px;">10 美麗的家鄉。</div>
  <div style="height: 200px;">11 美麗的家鄉。</div>
</body>
</html>

運作流程

關鍵字變了就重掃。用 oldKey 記住上次的關鍵字。一旦不同,先把先前的 .result 節點用 replaceWith($(this).html()) 還原成純文字,清空位置陣列,再用正則全域替換包上 <span class="result">。

記錄每個命中的 y 座標。掃描後巡一遍所有 .result,把 offset().top 存進 pos 陣列,之後跳轉就直接 scrollTop(pos[index])。

循環輪轉。index 到底就回到 0、往前超過頭就跳到最後一筆,模擬瀏覽器的環狀搜尋。

這段程式碼的三個嚴重問題

XSS。$("body").html($("body").html().replace(...)) 把整個頁面重寫成 HTML 字串,只要頁面上有任何使用者可控內容,就等於全面開放腳本注入。同時它也會摧毀頁面上所有已綁定的事件與狀態——輸入框的值、動畫、video 播放進度全都會歸零。

正則未轉義。使用者輸入 .、*、( 這類字元時,new RegExp(key) 會被當成語法而非普通字元,輕則搜尋結果錯誤,重則直接丟出例外。

搜尋範圍包含 script 與 style。直接掃 body 的 HTML 原始碼,會把 <script> 內容也一起替換掉,導致程式碼被汙染。

正確的做法

瀏覽器內建的搜尋之所以安全,是因為它操作的是文字節點而非 HTML 字串。要自己做,應該走 TreeWalker 遍歷文字節點:

var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
  acceptNode: function (node) {
    return /SCRIPT|STYLE/.test(node.parentElement.tagName)
      ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT;
  }
});
// 逐一檢查 node.nodeValue,命中時用 split + 建立 span 的方式包裝

這樣就不會碰觸標籤與事件,也不必擔心轉義問題。若只是想在自家頁面加搜尋,其實直接用內建的 window.find()(非標準但普遍支援)或提示使用者按 Ctrl+F,成本遠低於自己刻一套。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved