DIV CSS 佈局教程網

jQuery 實現網頁查找功能示例分享
編輯:JQuery特效代碼     

本文以查找車站名為例,仿照 12306 官網查找車站售票時間的效果:當用戶輸入關鍵字並點擊查找按鈕或按回車鍵時,jQuery 通過正則匹配內容,精準定位並滾動到第一個匹配的位置,同時顯示相關信息(本例中附加信息為車站的開始售票時間)。

HTML 結構

頁面需要一個輸入框、一個查找按鈕,以及包含若干 <p> 的主體內容 #content:

<div id="search_box">
    <input class="textbox" id="searchstr" type="text" size="10" name="searchstr" />
    <input class="sbttn" id="search_btn" type="button" value="頁內查找" />
</div>
<div id="content">
    <p><strong>8:00 起售車站</strong><br />
    安陽、白城、北京西、成都東、大慶……</p>
    <!-- 此處省略 n 個 p -->
</div>

CSS 樣式

其中 .highlight 用於設置查找結果的高亮樣式,#tip 用於設置信息提示框:

#search_box { background: white; opacity: 0.8; text-align: right; }
#search_btn { background: #0f79be; margin-top: 6px; border-radius: 2px;
    border: 0px; width: 100px; line-height: 24px; color: white; }
#searchstr { font-size: 14px; height: 20px; }
.highlight { background: yellow; color: red; }
#tip { background: #ffc; border: 1px solid #999; width: 110px;
    text-align: center; display: none; font-size: 12px; }

jQuery:固定查找框

首先封裝一個 fixDiv 方法,讓查找框在頁面滾動時始終固定在頂部,方便繼續查找:

(function ($) {
    $.fn.fixDiv = function (options) {
        var defaultVal = { top: 10 };
        var obj = $.extend(defaultVal, options);
        $this = this;
        var _top = $this.offset().top;
        var _left = $this.offset().left;
        $(window).scroll(function () {
            var _scrollTop = $(document).scrollTop();
            if (_scrollTop > _top) {
                $this.offset({ top: _scrollTop + obj.top, left: _left });
            } else {
                $this.offset({ top: _top, left: _left });
            }
        });
        return $this;
    };
})(jQuery);

// 調用
$(function () {
    $("#search_box").fixDiv({ top: 0 });
});

jQuery:綁定查找事件

點擊按鈕或在輸入框按回車鍵(keyCode 為 13)時,觸發查找函數 highlight():

$('#search_btn').click(highlight);
$('#searchstr').keydown(function (e) {
    var key = e.which;
    if (key == 13) highlight();
});

jQuery:核心查找邏輯

highlight() 需要完成:清空上次高亮、隱藏提示、判斷空輸入、正則匹配並高亮、定位並顯示提示信息等一系列工作:

var i = 0;
var sCurText;
function highlight() {
    clearSelection();   // 先清空上次高亮的內容
    var flag = 0;
    $('#tip').text('');
    $('#tip').hide();
    var searchText = $('#searchstr').val();
    var _searchTop = $('#searchstr').offset().top + 30;
    var _searchLeft = $('#searchstr').offset().left;
    if ($.trim(searchText) == "") {
        showTips("請輸入查找車站名", _searchTop, 3, _searchLeft);
        return;
    }
    // 創建正則,g 表示全局,否則找到第一個就停止
    var regExp = new RegExp(searchText, 'g');
    var content = $("#content").text();
    if (!regExp.test(content)) {
        showTips("沒有找到要查找的車站", _searchTop, 3, _searchLeft);
        return;
    } else if (sCurText != searchText) {
        i = 0;
        sCurText = searchText;
    }
    // 高亮顯示
    $('p').each(function () {
        var html = $(this).html();
        var newHtml = html.replace(regExp, '<span class="highlight">' + searchText + '</span>');
        $(this).html(newHtml);
        flag = 1;
    });
    // 定位並顯示提示信息
    if (flag == 1) {
        var _top = $(".highlight").eq(i).offset().top + $(".highlight").eq(i).height();
        var _left = $(".highlight").eq(i).offset().left;
        $("#tip").html(_tip).show().offset({ top: _top, left: _left });
        $("html, body").animate({ scrollTop: _top - 50 });
        i++;
        if (i > $(".highlight").size() - 1) { i = 0; }
    }
}

輔助函數

clearSelection() 用於清除高亮效果:

function clearSelection() {
    $('p').each(function () {
        $(this).find('.highlight').each(function () {
            $(this).replaceWith($(this).html());   // 去掉高亮 span
        });
    });
}

showTips() 用於顯示查找結果的提示信息:

var tipsDiv = '<div class="tipsClass"></div>';
$('body').append(tipsDiv);
function showTips(tips, height, time, left) {
    $('.tipsClass').text(tips);
    $('div.tipsClass').css({
        'top': height + 'px', 'left': left + 'px', 'position': 'absolute',
        'padding': '8px 6px', 'background': '#000000', 'font-size': '14px',
        'font-weight': 900, 'text-align': 'center', 'width': 'auto',
        'color': '#fff', 'border-radius': '2px', 'opacity': '0.8',
        'box-shadow': '0px 0px 10px #000'
    }).show();
    setTimeout(function () { $('div.tipsClass').fadeOut(); }, (time * 1000));
}

通過以上幾個部分的組合,就實現了一個具備高亮、定位滾動與信息提示的完整頁內查找功能。

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