页面搜索

 .res
        {
            color: Red;
        }
        .result{
            background: yellow;
        }
var oldKey = "";
         var index = -1;
         var pos = new Array();
         var oldCount = 0;
         function previous() {
             index--;
             index = index < 0 ? oldCount - 1 : index;
             searchTitle();
         }
         function next() {
             index++;
             if (index == oldCount) {
                 index = 0;
             }
             searchTitle();
         }
         function searchTitle() {
             $(".result").removeClass("res");
             var key = $("#key").val();
             if (!key) {
                 $(".result").each(function () {
                     $(this).replaceWith($(this).html());
                 });
                 oldKey = "";
                 return;
             }
             if (oldKey != key) {
                 index = 0;
                 $(".result").each(function () {
                     $(this).replaceWith($(this).html());
                 });
                 pos = new Array();
                 var regExp = new RegExp(key + '(?!([^<]+)?>)', 'ig');
                 var newHtml = $("#TreeView1").html().replace(regExp, "<span name='result" + index + "' class='result'>" + key + "</span>")
                 $("#TreeView1").html(newHtml);
                 $("#key").val(key);
                 oldKey = key;
                 $(".result").each(function () {
                     pos.push($(this).offset().top - 25);
                 });
                 if (pos.length > 0) {
                     $("#btnPrevious").prop("disabled", false);
                     $("#btnNext").prop("disabled", false);
                 }
                 oldCount = $(".result").length;
             }
             $("#spCount").text((index + 1).toString() + "/" + pos.length.toString());
             $(".result:eq(" + index + ")").addClass("res");
             $("html,body").animate({ scrollTop: pos[index] }, 1000);
         }
         function clsSearch() {
             if ($("#key").val() == "") {
                 $("#btnPrevious").prop("disabled", true);
                 $("#btnNext").prop("disabled", true);
                 $("#spCount").text("");
                 searchTitle();
             }
         }
<div style="position:fixed;left: 20px; top: 0px; background-color:#EFF6FE">
                搜索:<input id="key" type="text" style="width: 140px;" onkeydown="if(event.keyCode == 13) { next(); return false; }" onkeyup="clsSearch();" /><span id="spCount"></span>
                 <input type="button" value="上一个" onclick="previous()" id="btnPrevious" class="ButtonW"  disabled />
                <input type="button" value="下一个" onclick="next()"  id="btnNext" class="ButtonW" disabled/>
            </div>

特性:

1.搜索框回车进行搜索,并自动定位到结果首位。

2.点击上一个,下一个进行切换。

3.搜索框进行绝对定位。

4.搜索框清空时,自动清理上次搜索结果

posted @ 2024-12-26 13:32  Shapley  阅读(11)  评论(0)    收藏  举报