js–搜索框提示仿百度

大概要實現的內容

      這是一個很簡單的示例,服務器端隻是用瞭一個jsp頁面,返回的類型為xml。先講下是怎麼回事,就是在瀏覽器端,通過ajax請求,發送一串英文字母,服務器端通過比較,返回具有相同前綴的英文單詞。就這麼個意思。

      工程是在IntelliJ IDE中完成的。做前端開發感覺用IntelliJ比較方便,因為對於寫javascript的話,有函數名的提示。

      本例提供下載。望各位提出寶貴意見哈。

 

一、客戶端JSP頁面


Html代碼  收藏代碼

    <%– 
      Created by IntelliJ IDEA. 
      User: JayChang 
      Date: 2010-11-22 
      Time: 8:33:11 
      To change this template use File | Settings | File Templates. 
    –%> 
    <%@ page contentType="text/html;charset=UTF-8" language="java" %> 
    <html> 
      <head><title>AutoComplete-Sample</title> 
         <link type="text/css" rel="stylesheet" href="./css/default.css"> 
         <script type="text/javascript" src="./jslib/jquery-1.4.2.js"></script> 
         <script type="text/javascript" language="javascript"> 
             //高亮的索引 
             var highLightIndex = -1; 
             //超時的標識(對用戶連續快速按下鍵盤的事件做延時處理,隻對用戶在500ms內最後一次請求,讓其生效) 
             var timeoutId; 
             $(document).ready(function(){ 
                init(); 
                $('#auto_txt').bind('keyup',processKeyup); 
             }); 
     
             /** 
              * 處理鍵盤按下後彈起的事件 
              * @param event 
              */ 
             function processKeyup(event){ 
                   var myEvent = event || windows.event; 
                   var keyCode = myEvent.keyCode; 
                   //輸入是字母,或者退格鍵則需要重新請求 
                   if((keyCode >= 65 && keyCode <= 90) || keyCode =={ 
                        //以下兩行代碼是為瞭防止用戶快速輸入導致頻繁請求服務器 
                        //這樣便可以在用戶500ms內快速輸入的情況下,隻請求服務器一次 
                        //大大提高服務器性能 
                        highLightIndex = -1; 
                        clearTimeout(timeoutId); 
                        timeoutId = setTimeout(processAjaxRequest,500); 
                   //處理上下鍵(up,down) 
                   }else if(keyCode == 38 || keyCode == 40){ 
                       processKeyUpAndDown(keyCode); 
                   //按下瞭回車鍵 
                   }else if(keyCode == 13){ 
                       processEnter(); 
                   } 
              } 
     
             /*** 
              * 初始化彈出框列表的位置,大小 
              */ 
             function init(){ 
                $('#auto_p').hide(); 
                var pos = $('#auto_txt').position(); 
                var topPosition = pos.top+$('#auto_txt').height()+7; 
                var leftPosition = pos.left; 
                $('#auto_p').offset({top:topPosition,left:leftPosition}); 
                $('#auto_p').width($('#auto_txt').width()); 
                //$('#auto_p').css('position','absolute'); 
             } 
     
             /** 
              * 處理Ajax請求 
              * @param data 
              */ 
             function processAjaxRequest(){ 
                 $.ajax({ 
                     type:"post",       //http請求方法,默認:"post" 
                     url:"data.jsp",   //發送請求的地址 
                     data:"reqWord="+$('#auto_txt').val(), 
                     dataType:"xml",   //預期服務器返回的數據類型 
                     success:processAjaxResponse 
                  }); 
             } 
     
             /** 
              * 處理Ajax回復 
              * @param data Ajax請求得到的返回結果為dom文檔對象 
              */ 
             function processAjaxResponse(data){ 
                 $('#auto_p').html('').show(); 
                 var xml = $(data); 
                 var words = xml.find('word'); 
                 for(var i = 0 ; i < words.length ; i ++){ 
                    var word_p = $('<p></p>'); 
                    word_p.html(words.eq(i).text()); 
                    word_p.hover(fnOver,fnOut); 
                    word_p.click(getAutoText); 
                    $('#auto_p').append(word_p); 
                 } 
             } 
     
             /** 
              * 處理鼠標滑過 
              */ 
             function fnOver(){ 
                 //alert($(this)); 
                  changeToWhite(); 
                  $(this).css('background-color','pink'); 
                  //alert($(this).index()); 
                  highLightIndex = $(this).index(); 
                  //下面一行註釋掉瞭,百度搜索也沒這功能,就是鼠標移動時,跟著改變搜索框的內容 
                  //$('#auto_txt').val($('#auto_p').children().eq(highLightIndex).html()); 
             } 
              
             /** 
              * 處理鼠標移除 
              */ 
             function fnOut(){ 
                 $(this).css('background-color','white'); 
             } 
     
             /** 
              * 得到自動填充文本 
              */ 
             function getAutoText(){ 
                //有高亮顯示的則選中當前選中當前高亮的文本 
                if(highLightIndex != -1){ 
                    $('#auto_txt').val($(this).html()); 
                    $('#auto_p').html('').hide(); 
                } 
             } 
     
             /** 
              * 處理按下Enter鍵 
              * @param keyCode 
              */ 
             function processEnter(){ 
                 if(highLightIndex != -1){ 
                    $('auto_txt').val($('#auto_p').children().eq(highLightIndex).html()); 
                    $('#auto_p').html('').hide(); 
                 } 
             } 
     
             /** 
              * 處理按上下鍵的情況 
              */ 
             function processKeyUpAndDown(keyCode){ 
                 var words = $('#auto_p').children(); 
                 var num = words.length; 
                 if(num <= 0) return; 
                 changeToWhite(); 
                 highLightIndex = ((keyCode != 38 ? num + 1:num – 1)+highLightIndex) % num; 
                 words.eq(highLightIndex).css('background-color','pink'); 
                 $('#auto_txt').val(words.eq(highLightIndex).html()); 
             } 
     
             /** 
              * 如果有高亮的則把高亮變白 
              */ 
             function changeToWhite(){ 
                 if(highLightIndex != -1){ 
                     $('#auto_p').children().eq(highLightIndex).css('background-color','white'); 
                 } 
             } 
         </script> 
      </head> 
      <body> 
        自動完成示例 <input type="text" id="auto_txt"><input type="button" value="提交"> 
                     <p style="border-width:1px;" id="auto_p"></p> 
      </body> 
    </html> 

二、作為服務器端的JSP,返回的是XML

       這裡稍作解釋,為瞭方便起見,在服務器端隻是很簡單的處理,返回有相同前綴的英文單詞。沒有對空格等復雜的搜索條件作處理,本例主要還是側重於瀏覽器端的JavaScript。


Html代碼  收藏代碼

    <%– 
      Created by IntelliJ IDEA. 
      User: JayChang 
      Date: 2010-11-22 
      Time: 8:33:22 
      To change this template use File | Settings | File Templates. 
    –%> 
    <%@page contentType="text/xml; charset=UTF-8"%> 
    <% 
        String reqWord = request.getParameter("reqWord"); 
        System.out.println(reqWord); 
    %> 
    <words> 
        <%if("absolute".startsWith(reqWord)){%> 
            <word>absolute</word> 
        <%}%> 
        <%if("air".startsWith(reqWord)){%> 
            <word>air</word> 
        <%}%> 
        <%if("apple".startsWith(reqWord)){%> 
            <word>apple</word> 
         <%}%> 
        <%if("amaze".startsWith(reqWord)){%> 
            <word>amaze</word> 
         <%}%> 
        <%if("bat".startsWith(reqWord)){%> 
            <word>bat</word> 
         <%}%> 
        <%if("bicycle".startsWith(reqWord)){%> 
            <word>bicycle</word> 
         <%}%> 
        <%if("bite".startsWith(reqWord)){%> 
            <word>bite</word> 
         <%}%> 
        <%if("bottle".startsWith(reqWord)){%> 
            <word>bottle</word> 
         <%}%> 
        <%if("cat".startsWith(reqWord)){%> 
            <word>cat</word> 
         <%}%> 
        <%if("carry".startsWith(reqWord)){%> 
            <word>carry</word> 
         <%}%> 
         <%if("castle".startsWith(reqWord)){%> 
            <word>castle</word> 
         <%}%> 
    </words> 

   三、CSS樣式


Html代碼  收藏代碼

    #auto_p{ 
        position:absolute; 
        border-width:1px; 
        border:1px #808080 solid; 
    }  

 

本文出自“stevenjohn”

You May Also Like