搜索框--自動提示(仿Baidu)(一)


以前看見百度搜索這種功能感覺很炫,自己想做一個出來備用,試着做過沒有做出來,這次項目必須要用就做了一個demo出來,比較簡陋但是可以再此基礎上做修改應該比較容易了,現在發出來分享給大家。也不知道這個算不算用了ajax)。

  

  1、首先是要查詢的后台數據,直接用了寫死的數據,要變化也容易了

View Code
protected void Page_Load(object sender, EventArgs e)
    {
        WriteResult();
    }

    private void WriteResult()
    {
        string strurl = Request.RawUrl;

       List<string> strList = new List<string>();
        strList.Add("成都");
        strList.Add("廣都");
        strList.Add("京都");
        strList.Add("都督");
        strList.Add("都護");
        strList.Add("拿督");

        List<string> list=new List<string>();

        string strRequest = string.Empty;
        strRequest = Request.QueryString[0].Trim();

        if (string.IsNullOrEmpty(strRequest)) 
        { Response.Write(";");
        return;
        }

      foreach (string item in strList)
        {
            if (item.Contains(strRequest)) list.Add(item);
        }

        string strResult = string.Empty;

        foreach (string value in list)
        {
            strResult += value + ";";
        }

        Response.Write(strResult);
    }

  2、搜索提示的前台頁面

View Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>搜索提示框演示(一)</title>

    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>

    <script type="text/javascript">    
    
//    function fun()
//    {
//        document.getElementById("txtDate").innerText="A";
//    }
//    
//    function ClearAll()
//    {
//        document.getElementById("txtDate").innerText="AAA";
//        document.getElementById("txtd").innerText="BBB";
//        return false;
//    }
//    
//    window.onload=function()
//    {
//        document.getElementById("txtDate").innerText="gg";
//        document.getElementById("txtd").value="uuuuu";
//        
//        document.getElementById("txtmsg").value=document.getElementById("txtDate").innerHTML;
//    }
//    
    
    
    
    
     
     var array=new Array(); //定義一個全局變量數組,用來存放拆分字符串的值,后面具體介紹。
        var zz=-1; //此為指針,后面用到
        var count=-1;//搜索結果個數
        
        var keyupdown=-1;//記錄鍵盤 onkeyup 和onkeydown 
        
function xmlHttpInitializtions()
        {
            try 
            {
                xmlhttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } 
            catch (e) 
            {
                try 
                {
                    xmlhttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch (e2) 
                {
                    xmlhttpRequest = false;
                }
            }
            if (!xmlhttpRequest && typeof XMLHttpRequest != 'undefined') 
            {
                xmlhttpRequest = new XMLHttpRequest();
            }
        }
        

function beKeydown()
{
//     if(event.keyCode==38||event.keyCode==40)
//        {
//            for(var l=0;l<count;l++)
//            {
//                document.getElementById("item" + l).className="item_normal";
//            }
//        beShow();
//        return false;
//        }
        
}
        
function beKeyUp()
        {
        if(event.keyCode==37||event.keyCode==39) return false;

        if(event.keyCode==38||event.keyCode==40)
        {
            
            for(var l=0;l<count;l++)
            {
                document.getElementById("item" + l).className="item_normal";
            }
            beShow();
            return false;
        }       
            
            var key = document.getElementById("txtSearch").value;
            if(key.length>0)//有值才POST,這里最好加個Trim()方法,但是JAVASCRIPT沒有現成的方法,自己定義。
            {
                xmlHttpInitializtions();
                document.getElementById("txtmsg").value=key;
                xmlhttpRequest.Open("Post","GetResult.aspx?name=" + encodeURI(key),true);//POST
                xmlhttpRequest.onreadystatechange=stateChange;//返回狀態調用方法stateChange
                xmlhttpRequest.Send();
            }
            else
            {
                document.getElementById("search_suggest").innerHTML="";
            }
        }
        function stateChange()
        {
            if(xmlhttpRequest.readystate==4)
            {
                if(xmlhttpRequest.status==200)
                {
                    var responseStr=xmlhttpRequest.responseText;//獲取返回值
                    document.getElementById("search_suggest").style.display="block";
                    count=-1;
                    if(responseStr.length>0)//返回值不為空才執行下面的代碼
                    {
                        array=responseStr.split(';');//根據‘|’拆分,根據自己任意特殊字符,初始化數組
                        positionDiv();//調用方法,定位DIV顯示,具體見方法解釋
                        document.getElementById("search_suggest").innerHTML="";//每次清空DIV內容
                        
                        count=array.length-1;//------------------
                        for(var i=0;i<array.length;i++)
                        {
                            if(array[i]!=""&&array[i]!=" ")//項值不為空,組合DIV,每個DIV有onmouseover、onmouseout、onclick對應事件
                            {
                                if(i<array.length-2)  
                                document.getElementById("search_suggest").innerHTML+="<div id='item" + i + "' class=' itemBg'   onmouseover=' beMouseOver(" + i +")' onmouseout=' beMouseOut(" + i + ")' onclick=' beClick(" + i + ")'>" + array[i] + "</div>";
                                else
                                document.getElementById("search_suggest").innerHTML+="<div id='item" + i + "' class='itemBg' style='border-bottom: #666 1px solid;' onmouseover='beMouseOver(" + i +")' onmouseout='beMouseOut(" + i + ")' onclick='beClick(" + i + ")'>" + array[i] + "</div>";                                
                            }
                            document.getElementById("txterror").value+=document.getElementById("search_suggest").innerHTML;
                           
                        }
                         //document.getElementById("txterror").value=document.getElementById("search_suggest").innerHTML;  為什么這兒取不到值呢?
                    }
                    else
                    {
                        document.getElementById("search_suggest").style.display="none";
                    }
                }
            }
        }
        //定位DIV顯示
function positionDiv()
        {
              var DivRef= document.getElementById("search_suggest");
              DivRef.style.position = "absolute";
              var t=document.getElementById("txtSearch");
              DivRef.style.top= getAbsolutePos(t).y;//相對文本框的TOP高度,方法見下面
              DivRef.style.left= getAbsolutePos(t).x ;//相對文本框的LEFT寬度
              DivRef.style.height=(array.length-1) * 20;//DIV的高度等於每行20個象素乘行數(也就是數組的長度,體現全局數組的作用,不然要傳入數組長度的參數)
        }
//實現最后一個DIV 關閉 onclick方法
function hiddenDiv()
        {
            document.getElementById("search_suggest").style.display="none";
        }
//定位方法,不做解釋
function getAbsolutePos(el)
        {
            var SL = 0, ST = 0;
            var is_div = /^div$/i.test(el.tagName);
            if (is_div && el.scrollLeft) SL = el.scrollLeft;
            if (is_div && el.scrollTop) ST = el.scrollTop;
            var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
            if (el.offsetParent)
            {
                var tmp = this.getAbsolutePos(el.offsetParent);
                r.x += tmp.x;
                r.y += tmp.y;
            }
            return r;
        }

        //最后是鼠標效果的方法。
        //函數鼠標經過效果        
        function beMouseOverEFF(i)
        {
            if ((i>=0)&(i<=array.length-1))
            {
                document.getElementById("item" + i).className="item_high";
            }
        }

        //函數鼠標移開效果
        function beMouseOutEFF(i)
        {
            if ((i>=0)&(i<=array.length-1))
            {
                document.getElementById("item" + i).className="item_normal";
            }                        
        }

        //函數鼠標經過
        function beMouseOver(i)
        {
            document.getElementById("txtSearch").focus();
            
            for(var l=0;l<count;l++)
            {
                document.getElementById("item" + l).className="item_normal";
            }
            
            //beMouseOutEFF(zz);
            zz=i;
            beMouseOverEFF(zz);
            
        }

        //函數鼠標移開
        function beMouseOut(i)
        {
            beMouseOutEFF(i);
            
        }
        //函數單擊
        function beClick(i)
{
            document.getElementById("txtSearch").value=array[i];
            document.getElementById("search_suggest").style.display="none";
            document.getElementById("txtSearch").focus();
        }
    
//點擊頁面其他位置關閉搜索結果    
function beClose()
{
    document.getElementById("search_suggest").style.display="none";
}
 
 //上下鍵盤
 function beShow()
 {    
    if(event.keyCode==38)
    {       
         zz=(zz+count-1)%count; 
         document.getElementById("item" + zz).className="item_high";
         document.getElementById("txtSearch").value=document.getElementById("item" + zz).innerHTML;
         return false;
         
    }
    else if(event.keyCode==40)
    {
         zz=(zz+count+1)%count;     
         document.getElementById("item" + zz).className="item_high";
         document.getElementById("txtSearch").value=document.getElementById("item" + zz).innerHTML;
         return false;
        
    }
    else if(event.keyCode==13)
    {
        alert(13);
    }
     
 }   
    </script>

    <style type="text/css">

    
    
    
    
    .item_normal
{
    BORDER-LEFT: #666 1px solid;
    BORDER-RIGHT: #666 1px solid;
    width:204px;
    background-color:#ffffff;
    overflow:visible;
}
.itemBg
{
    BORDER-LEFT: #666 1px solid;
    BORDER-RIGHT: #666 1px solid;
    cursor:default;
    background-color:#ffffff;
    width:204px;
}
.item_high
{
    background-color:#326BC5;
    BORDER-LEFT: #666 1px solid;
    BORDER-RIGHT: #666 1px solid;
    cursor:default;
    width:204px;
    color:white;
}
.item_button
{
    BORDER-LEFT: #666 1px solid;
    BORDER-RIGHT: #666 1px solid;
    BORDER-BOTTOM: #666 1px solid;
    text-align:right;
    background-color:#ffffff;
    width:204px;
    cursor:hand;
}
.suggest_hidden
{
    display:none;
}

    </style>
</head>
<body style="height: 100%; width: 100%;" onclick="beClose();">
    <form id="form1" runat="server">

        <asp:TextBox ID="txtSearch" runat="server" autocomplete="off"  onkeyup="return beKeyUp();"  onkeydown="beKeydown();"
             Width="200px"></asp:TextBox>
        <div id="search_suggest" style="position: absolute; z-index: 1; padding: 22px 0px 0px 0px;">
        </div>
        <asp:Button ID="btnSearch" runat="server" Text="查詢" />
        <asp:TextBox ID="txtmsg" runat="server"></asp:TextBox>
        <asp:TextBox ID="txterror" runat="server" Width="700px" Height="500px" TextMode="MultiLine"></asp:TextBox>
    </form>
</body>
</html>


   對js不太熟悉,做起來很吃力,在VS2005調試就更悲催了。目前任然沒解決的是onkeydown事件的處理(一直按住一個鍵),先觸發onkeydown然后是onkeyup。。。希望大家指點指點或者提出各種意見。

 

  PS:不知道百度用的什么方式整出來的。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM