jQuery实现页内查找相关内容

时间 : 14-09-27 栏目 : js知识 作者 : admin 点击 : 2,947 次

当需要在页面中查找某个关键字时,一是可以通过浏览器的查找功能实现,二是可以通过前端脚本准确查找定位,本文介绍通过jQuery实现的页面内容查找定位的功能,并可扩展显示查找后的相关信息。

本文以查找车站名为例,仿12306官网查找车站售票时间页面效果,当用户输入关键字点击查找按钮或按回车键时,jQuery通过正则匹配内容,准确匹配关键字,并迅速将页面定位滚动到第一个匹配的位置,并显示相关信息(本例中附加信息为车站开始售票时间)。

HTML

页面需要放置一个输入框用来输入要查找的关键字,以及一个查找按钮,然后就是主体内容#content,里面包含着n个<p>,即每个时间段开售车票的车站名。

<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

简单的对页面内容进行CSS设置,其中.highlight和#tip分别用来设置查找结果高亮显示和信息提示框显示的样式效果,后面我们会介绍到。

#search_box { background: white; opacity: 0.8text-align:right } 
#search_btn { background: #0f79bemargin-top: 6px; border-radius: 2pxborder: 0px;  
width: 100pxline-height: 24pxcolor: white; } 
#searchstr { font-size: 14pxheight: 20px; } 
.highlight { background: yellowcolor: red; } 
#tip { background: #ffcborder: 1px solid #999width: 110pxtext-align: center;  
display: nonefont-size: 12px; } 

jQuery

首先,我们要实现一个固定div的效果,就是当页面往下拉滚动时,用于查找的输入框和按钮始终固定在页面的最顶部,方便继续查找。

(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 _currentTop = $this.offset().top; 
            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); 

接着,我们调用fixDiv()。

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

接下来,最关键的实现查找功能。当输入关键字后,点击查找按钮或按回车键,调用查找函数highlight()。

$(function(){ 
    ... 
    $('#search_btn').click(highlight);//点击search时,执行highlight函数; 
    $('#searchstr').keydown(function (e) { 
        var key = e.which; 
        if (key == 13) highlight(); 
    }) 
    ... 
}); 

在函数highlight()需要做很多事情,1.清空上次高亮显示内容,2.隐藏并清空提示信息,3.判断输入内容为空的情况,4.获取输入的关 键字,并与页面内容进行正则匹配,并用flag标记查找到结果,将查找结果高亮显示,5.根据查找结果的数量,确定提示信息的内容和位置偏移量,准确定位 并显示提示信息。请看具体代码:

$(function(){ 
    ... 
    var i = 0; 
    var sCurText; 
    function highlight(){ 
        clearSelection();//先清空一下上次高亮显示的内容; 
         
        var flag = 0; 
        var bStart = true; 
         
        $('#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; 
        } 
        //查找匹配 
        var searchText = $('#searchstr').val();//获取你输入的关键字; 
        var regExp = new RegExp(searchText, 'g');//创建正则表达式,g表示全局的,如果不用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(); 
            //将找到的关键字替换,加上highlight属性; 
            var newHtml = html.replace(regExp, '<span class="highlight">'+searchText+'</span>'); 
            $(this).html(newHtml);//更新; 
            flag = 1; 
        }); 
         
        //定位并提示信息 
        if (flag == 1{ 
            if ($(".highlight").size() > 1{ 
                var _top = $(".highlight").eq(i).offset().top+$(".highlight").eq(i).height(); 
                var _tip = $(".highlight").eq(i).parent().find("strong").text(); 
                if(_tip=="") _tip = $(".highlight").eq(i).parent().parent().find("strong").text(); 
                var _left = $(".highlight").eq(i).offset().left; 
                var _tipWidth = $("#tip").width(); 
                if (_left > $(document).width() - _tipWidth) { 
                     _left = _left - _tipWidth; 
                } 
                $("#tip").html(_tip).show(); 
                $("#tip").offset({ top: _top, left: _left }); 
                $("#search_btn").val("查找下一个"); 
            }else{ 
                var _top = $(".highlight").offset().top+$(".highlight").height(); 
                var _tip = $(".highlight").parent().find("strong").text(); 
                var _left = $(".highlight").offset().left; 
                $('#tip').show(); 
                $("#tip").html(_tip).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(){ 
            //找到所有highlight属性的元素; 
            $(this).find('.highlight').each(function(){ 
                $(this).replaceWith($(this).html());//将他们的属性去掉; 
            }); 
        }); 
} 

最后加上showTips()函数,该函数用来显示在输入查找关键字后的查找结果提示信息。

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

除非注明,文章均为( admin )原创,转载请保留链接: http://www.pnyes.com/?p=42