实现google的下拉列表效果

时间:2022-03-03 10:12:57

最简做了个实现google下拉效果的程序,这样的程序网上挺多,但是代码不少,需要慢慢看。这里贴一下我的,这个代码借鉴 http://www.cnblogs.com/ustb*/archive/2006/07/17/452700.aspx的博客的代码,做了一下必要的修改。

1 js代码,这个代码主要是对于下拉列表的生成和操作,以及调用ajax接口

var menuFocusIndex;  //当前选中行
var arrylist;//当前返回数组
var resultlength=0;//当前数组长度
function getPosition(obj)//获取当前操作坐标
{
    var top = 0,left = 0;
    do
    {
       top += obj.offsetTop;
       left += obj.offsetLeft;
    }
    while ( obj = obj.offsetParent );     
    var arr = new Array();     
    arr[0] = top;
    arr[1] = left;   
    return arr;   
}

function createMenu(result)//生成div

    var textBox=document.getElementById("inputer");
    var menuid="divout";
    var divouter;
   if( document.getElementById(menuid) == null )
   {
        var left_new=getPosition(textBox)[1];
        var top_new=getPosition(textBox)[0];   
        var newControl = document.createElement("div");
        newControl.id = menuid;       
        document.body.appendChild(newControl);
        newControl.style.position = "absolute";
        newControl.style.border = "solid 1px #0000ee";
        newControl.style.backgroundColor = "#FFFFFF";
        newControl.style.width = 158 + "px";
        newControl.style.left = left_new + "px";        
        newControl.style.top = top_new+ 2 +20+ "px";
        try{
        newControl.style.font=12+"px";}
        catch(err){}
        divouter= newControl;
   }
   else
      divouter= document.getElementById( menuid );
   divouter.innerHTML =result;
}

function createMenuBody(resultlist)//根据返回数组生成div中行
{

    var result="";
    var j = 0;
    arr = resultlist;
   arrylist =arr;
    if(arr.length > 10)
    {
        j = 10;
    }
    else
    {
       j = arr.length;
    }
    resultlength=j;
   if(j-1 >0)
   {
        for ( var i = 0; i < j-1; i++ )
        result += "<table border="0" cellpadding="2" cellspacing="0" id="menuItem"+(i+1)+"" onmouseover="forceMenuItem( "+(i+1)+");" width="100%" onclick="givNumber("+i+")"><tr><td align="left">" + arr[i] + "</td><td align="right">" + (i+1) + " </td></tr></table>";
       createMenu(result);
   }
   else
   {
       var div = document.getElementById("divout");
       if(div)
       div.parentNode.removeChild(div); 
   }
}
function forceMenuItem(index)//div中颜色变化
{
    lastMenuItem = document.getElementById("menuItem" + menuFocusIndex);
    if (lastMenuItem != null)
    {
        lastMenuItem.style.backgroundColor="white";      
        lastMenuItem.style.color="#000000";
    }
    var menuItem = document.getElementById("menuItem" + index);
    if (menuItem == null)
    {
        document.getElementById("txt1").focus();
    }
    else
    {
        menuItem.style.backgroundColor = "#5555CC";
        menuItem.style.color = "#FFFFFF";
        menuFocusIndex = index;
    }
}
function givNumber(index)//鼠标事件对应文本框赋值
{
    document.getElementById("inputer").value =  arrylist[index];
    document.getElementById("inputer").focus();
    var div = document.getElementById("divout");
    div.parentNode.removeChild(div);                 
}
function givNumberbykey(index)//按键事件对应文本框赋值
{
    document.getElementById("inputer").value =  arrylist[index];
    document.getElementById("inputer").focus();
    //var div = document.getElementById("divout");
    //div.parentNode.removeChild(div);                 
}
function catchKeyBoard()//按键事件
{
   var keyNumber = event.keyCode;
   if(keyNumber=='40') //向下
   {    
            if (menuFocusIndex==null) //当焦点在文本框中间时,按向下跳到第一个主体。
            {
               forceMenuItem(1);
               givNumberbykey(0);
            }
            else if(menuFocusIndex==resultlength-1)//当焦点超出界限时跳转到第一个主体
            {
               forceMenuItem(1);
               givNumberbykey(0);
            }
            else
            {
               forceMenuItem(menuFocusIndex+1); //焦点增加1
               givNumberbykey(menuFocusIndex-1);
            }
   }
   else if(keyNumber=='38')//向上
   {
  
        if(menuFocusIndex==1)
         {
            forceMenuItem(resultlength-1);
            givNumberbykey(resultlength-2);  
           // forceMenuItem(menuFocusIndex-1); //当焦点在第一个主体时,按向上让它回到文本框。
         }
        else
        {
           forceMenuItem(menuFocusIndex-1); //焦点减少1
           givNumberbykey(menuFocusIndex-1);
        }
  }
  else if(keyNumber=='13')
  {
        givNumber(menuFocusIndex-1);
  }
}

function DisplayUserInformation()//ajax方法调用
{
   var keyNumber = event.keyCode;
   if(keyNumber=='40'||keyNumber=='38'||keyNumber=='13')
     catchKeyBoard();
   else
   {
       var url = "";
       var canshu=document.getElementById("inputer").value;
       if(canshu!="")
       {
            url = '../WebForm9.aspx?qs='+canshu;
            Ajax.Request(url,pareseResultText,null,null,'text',null,'' ); 
       }
       else
       {
           var div = document.getElementById("divout");
           if(div)
           div.parentNode.removeChild(div); 
       }
   }
}

function pareseResultText()//ajax方法获取
{
    var result = this.req.responseText;
    if(result)
    {
        eval(result);
    }
}

function CreateUserInfo(objResult)//ajax方法数组接收
{
    if(objResult)
    {
       var result = new Array(); 
            for(var obj in objResult)
            {
               result = objResult[obj].split('~');
               createMenuBody(result);
            }        
       }
}

2 公用js的ajax对象,由上一部分代码调用


//
//公用Ajax请求对象
//
var Ajax = {
    LoadContent:function(url,onload,onerror,sendData,dataType,requestType,callBackGuid)
    {
        this.url = url;
        this.req = null;
        this.data;
        this.onload = onload ;
        this.onerror = onerror?onerror:this.defaultError;
        this.sendData = sendData;
        this.dataType =dataType || "xml";
        this.requestType = requestType;
        this.callBackGuid = callBackGuid;

        this.LoadXml(url);

    },
    Request:
    function(url,onLoad,onError,
        sendData,dataType,requestType,callBackGuid){
  
        new  Ajax.LoadContent(url,onLoad,onError,sendData,dataType,requestType,callBackGuid);
    },
    ProcSubmit :
    function(url,fromId,onCallBack,onError,callBackGuid)
    {
        var obj=$(fromId);
        var str="";
        for(i=0;i<obj.elements.length;i++)
        { 
            e=obj.elements[i];
            if(e.type=="text"
            ||e.type=="hidden"
            ||e.type=="textarea"
            ||e.type=="password"){
                str+="&"+e.name+"="+escape(e.value);
            }else if(e.type=="radio"){
                if(e.checked){
                    str+="&"+e.name+"="+escape(e.value);
                }
            }else if(e.type=="select-one"){
                str+="&"+e.id+"Id="+escape(e.options[e.selectedIndex].value);
                str+="&"+e.id+"Name="+escape(e.options[e.selectedIndex].text);
            }
        }
        str=str.replace(str.substring(0,1),"");
        Ajax.Request(url,onCallBack,onError,str,'text',null,callBackGuid);
    }
}

//
//自定义内容属性
//
Ajax.LoadContent.prototype ={
    LoadXml:function(url){
        if(window.ActiveXObject){
            for(var i in this.XmlHttpType){
                    try{
                        this.req = new ActiveXObject(this.XmlHttpType[i]);break;
                    }catch(e){
                        continue;
                    }
                }
            }else if(window.XMLHttpRequest){
                    this.req = new XMLHttpRequest();
             }
             if(this.req){
                var tempLoad = this;
                this.req.overrideMimeType?this.req.overrideMimeType("text/xml"):null;
                this.req.onreadystatechange =function(){
                    tempLoad.ReadyStateChange.call(tempLoad);
             }
            if(this.sendData){
                this.req.open("POST",this.url,true);
                if(this.requestType && this.requestType.toLowerCase()=="xml"){
                    this.req.setRequestHeader("Content-Type","text/xml; charset=gb2312");
                }
                else{
                    this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                }
            }else{
                this.req.open("GET",this.url+'&xmlRequest=cmd',true);//temp add cmd
            }
            if(this.requestType
            &&this.requestType.toLowerCase()=="xml"){
                  this.req.send(this.sendData);
            }
            else{
                  this.req.send(this.sendData);
            }
         }
            
    },
    XmlHttpType:{
        msxml2:"MSXML2.XMLHTTP",
        msxml2_5:"MSXML2.XMLHTTP.5.0",
        msxml2_3:"MSXML2.XMLHTTP.3.0",
        msxml2_4:"MSXML2.XMLHTTP.4.0",
        micxmlhttp:"Microsoft.XMLHTTP"
     },
     ReadyStateChange:function(){
        if(this.req.readyState == 4){
            if(this.req.status == 200 || this.req.status == 0){
                if(this.dataType.toLowerCase()=="xml"){
                }else{
                }
                this.onload.call(this,this.callBackGuid);
            }else{
                this.onerror.call(this);
            }
        }
       
     },
     GetLoadData:function(){
        return this.data;
     },
     defaultError:function(){
        alert('error .. ResponseHeads='+this.req.getAllResponseHeaders());
     }
}
Ajax.pro =function (){alert('f');}
3 页面中事件引发按钮

<input id="inputer" type="text"  onkeyup= "DisplayUserInformation()"  style="width: 158px; height: 20px"/>
4 后台代码逻辑处理,返回str字符串

 private void inidata()
        {
            string requeststring = Request.QueryString["qs"].Trim().Replace(" ","").Replace(" ","");
            string str = string.Empty;
            DataTable dt = Class1.getdataview();
            str = "CreateUserInfo({12:'";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["学生班级"].ToString().StartsWith(requeststring))
                    str += dt.Rows[i]["学生班级"] + "~";
            }
            str += "'})";
            EndResponse(str);
        }
        private void EndResponse(string val)
        {
            Response.Clear();
            Response.Write(val);
            Response.Flush();
            Response.End();
        }
至此google的下拉功能大致实现,至于后台搜索关键字的方法当然是随便写的。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/keyake863/archive/2008/04/09/2268496.aspx