Jquery to achieve web search function example sharing

  • 2020-03-30 01:39:36
  • OfStack

This paper to find the station called example, page 12306 official website to find the station ticket time effect, when the user to enter the keywords, click on the search button or press the return key, jQuery through regular matching content, accurate matching keywords, and the page quickly locate the position of the scroll to the first matching, and display the relevant information (in this case, additional information for the station at ticket time).

HTML

The page needs to have an input field for the keyword to look for, a search button, and then the main content #content, which contains n < P> , is the name of the station where tickets are sold at each time period.
 


<div id="search_box"> 
    <input class="textbox" id="searchstr" type="text" size="10" name="searchstr" />  
    <input class="sbttn" id="search_btn" type="button" value=" Pages to find " /> 
</div> 
<div id="content"> 
    <p><strong>8 : 00  Starting at the station </strong><br /> 
 Anyang, baicheng, Beijing west, chengdu east, daqing, daqing west, dongguan, dongguan east, huizhou, jinhuanan, jinyun, jiujiang, lanzhou, lishui, linfen, nanchong  
 Qiqihar, qingtian, rizhao, shanhaiguan, shantou, songyuan, wenzhou, ulanhot, urumqi, wuchang, wuyi, xi 'an, yongkang, yuncheng. </p> 
    .... Is omitted n a p 
</div> 

CSS

Simply set the CSS for the content of the page, where. Highlight and #tip are used to set the style effect for highlighting the search results and displaying the message box respectively, which we will discuss later.


#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

First, we want to achieve a fixed div effect, that is, when the page scroll down, the search for the input box and button is always fixed at the top of the page, to facilitate the search.

 


(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); 

Next, we call fixDiv().

 


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

Next, the most critical implementation of the lookup function. When a keyword is entered, click the find button or press enter to call the find function highlight().

 


$(function(){ 
    ... 
    $('#search_btn').click(highlight);//When you click search, execute the highlight function;
    $('#searchstr').keydown(function (e) { 
        var key = e.which; 
        if (key == 13) highlight(); 
    }) 
    ... 
}); 

Highlight the function () needs to do a lot of things, 1. Empty the highlighted content last time, 2. Hide and clear message, (3) determine the input is empty, 4. Obtain input keywords, and regular matching with the page content, and the flag to mark as a result, to find the search results highlighted, 5. According to the number of search results, determine the content of the message and position offset, accurate positioning and displays a message. Please see the specific code:


$(function(){ 
    ... 
    var i = 0; 
    var sCurText; 
    function highlight(){ 
        clearSelection();//Let's clear out what was highlighted last time;

        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(" Please enter the name of the station ",_searchTop,3,_searchLeft); 
            return; 
        } 
        //To find the matching
        var searchText = $('#searchstr').val();//Get the key you entered;
        var regExp = new RegExp(searchText, 'g');//Create a regular expression, g for global, if you don't use g,
                  //If I find the first one, I'm not going to go down;
        var content = $("#content").text(); 
        if (!regExp.test(content)) { 
            showTips(" The station was not found ",_searchTop,3,_searchLeft); 
            return; 
        } else { 
            if (sCurText != searchText) { 
                i = 0; 
                sCurText = searchText; 
             } 
        } 
        //The highlighted
        $('p').each(function(){ 
            var html = $(this).html(); 
            //Replace the keyword found with the highlight attribute;
            var newHtml = html.replace(regExp, '<span class="highlight">'+searchText+'</span>'); 
            $(this).html(newHtml);//Update;
            flag = 1; 
        }); 

        //Locate and prompt the message
        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(" Find the next one "); 
            }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; 
            } 
        } 
    } 
      ... 
}); 

The clearSelection() function mentioned in the above code is used to clear the highlighting effect, as follows:

 


function clearSelection(){ 
        $('p').each(function(){ 
            //Find the elements of all the highlight attributes;
            $(this).find('.highlight').each(function(){ 
                $(this).replaceWith($(this).html());//Remove their attributes;
            }); 
        }); 
} 

Finally, add the showTips() function, which displays the search result prompt after the search keyword is entered.

 


$(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 ) );  
    }  
}); 


Related articles: