关于js智能提示的封装(修订版)

修改后的智能提示,下拉框的样式兼容了IE6,7,8,9.  没有了之前的css文件和下拉框的html代码。清除了textbox的记忆功能和点击enter时页面回传。只须一个Bonker.js文件即可。
           使用非常简单调用bonker.js文件里面的 init(id, url, fun);的方法。
           说明:id为输入框的客户端id,url为ajax响应的地址。多条数据用逗号分隔。fun为当选择下拉框的一条数据后执行的函数
                    id和url为必须传的参数。fun为可选参数。没有则不用填写
 
js文件代码:
                               bonker.js文件内容
//初始化,为text绑定事件,定义url,回调函数fun(可选)
var bonkerDiv;
var bonkerFun;
var txtId;
function init(id, url, fun) {
    txtId = id;
    if (url) {
        bonkerUrl = url;
    } else { return; } if (fun) {
        bonkerFun = fun;
    }
    textControl = document.getElementById(id);
    //清除输入框记忆功能
    textControl.autocomplete = "off";
    if (textControl.attachEvent) {
        textControl.attachEvent("onkeyup", main);
        textControl.attachEvent("onkeypress", pressEnter);
    } else {
        textControl.addEventListener("keyup", main, false);
        textControl.addEventListener("keypress", pressEnter, false);
    }
}
//阻止输入enter,页面回传
function pressEnter(ev) {
    if (window.event) {
        ev = window.event;
    }
    if (ev.keyCode == 13) {
        if (navigator.userAgent.indexOf("MSIE") > 0)
            ev.returnValue = false;
        else
            ev.preventDefault();
    }
}
//处理键盘事件主要是enter  向上 向下键
function main(ev) {
    if (window.event) {
        ev = window.event;
    }
    if (ev.keyCode == 40) {
        divNext();
    } else if (ev.keyCode == 38) {
        divPre();
    } else if (ev.keyCode == 13) {
        bonkerFunction();
        bonkerDiv.style.display = "none";
        return false;
    }
    else {
        bonkerData = textControl.value;
        if (bonkerData.length == 0 && bonkerDiv) {
            bonkerDiv.style.display = "none";
        } else {
            getData(textControl.value, textControl);
        }
    }
}

//创建xmlhttp对象
var xhr = function () {
    if (!arguments.callee.single) {
        var fns = [
      function () { return new XMLHttpRequest(); },
      function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
      function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
    ];
        for (var i = 0, n = fns.length; i < n; i++) {
            try {
                fns[i]();
                arguments.callee.single = fns[i];
                break;
            } catch (e) { }
        }
        return arguments.callee.single();
    } else {
        return arguments.callee.single();
    }
}
//ajax获取数据 数据以逗号分开
function getData(va, obj) {
    var xmlHttp = xhr();
    xmlHttp.open("POST", bonkerUrl, true);
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            showData(obj, xmlHttp.responseText);
        }
    }
    xmlHttp.send(va);
}


//兼容获取offsetTop和offsetLeft
function getAbsoluteOffsetTop(obj) {
    var top = obj.offsetTop;
    while (obj = obj.offsetParent) top += obj.offsetTop;
    return top;
}
function getAbsoluteOffsetLeft(obj) {
    var left = obj.offsetLeft;
    while (obj = obj.offsetParent) left += obj.offsetLeft;
    return left;
}
//展示数据,动态生成下拉框,为每个选项绑定事件
function showData(obj, result) {
    var resArr = result.split(",");
    bonkerDiv = document.getElementById("showDivBonker");
    if (!bonkerDiv) {
        bonkerDiv = document.createElement("div");
        bonkerDiv.id = "showDivBonker";
        bonkerDiv.style.display = "none";
        bonkerDiv.style.position = "absolute";
        bonkerDiv.style.border = "1px solid #817F82";
        bonkerDiv.style.zIndex = "9999";
        bonkerDiv.style.backgroundColor = "#ffffff";
        document.body.appendChild(bonkerDiv);
        var bonkerBody = document;
        if (bonkerBody.attachEvent) {
            bonkerBody.attachEvent("onmousedown", showBonkerBlur);
        } else {
            bonkerBody.addEventListener("mousedown", showBonkerBlur, false);
        }
    }
    var bonkerTop = getAbsoluteOffsetTop(obj);
    var bonkerLeft = getAbsoluteOffsetLeft(obj);

    bonkerDiv.style.top = (bonkerTop + obj.offsetHeight) + "px";
    bonkerDiv.style.left = bonkerLeft + "px";
    bonkerDiv.style.width = obj.offsetWidth + "px";
    bonkerDiv.style.height = obj.offsetHeight * resArr.length + "px";
    bonkerDiv.style.display = "inline";
    bonkerTotalLength = resArr.length;
    bonkerLength = -1;
    var innerStr = "";
    for (var item in resArr) {
        innerStr += "<div id='bonker" + item + "' style='height:" + obj.offsetHeight + "px;cursor:pointer;width:100%;' onclick='setText(this);' onmouseover='setColor(this);' onmouseout='clearColor(this);'>" + resArr[item] + "</div>";
    }
    bonkerDiv.innerHTML = innerStr;
}

function showBonkerBlur(ev) {
    var divTarget = ev.srcElement ? ev.srcElement : ev.target;
    if (divTarget.id.indexOf("bonker") < 0 && divTarget.id != txtId)
        bonkerDiv.style.display = "none";
}
//点击每个选项执行的函数
function setText(obj) {
    textControl.value = obj.innerHTML;
    bonkerFunction();
    bonkerDiv.style.display = "none";
}
//鼠标移动到选项执行
function setColor(obj) {
    if (bonkerLength != -1) {
        document.getElementById("bonker" + bonkerLength).style.backgroundColor = "";
    }
    obj.style.backgroundColor = "#EBEBEB";
    bonkerLength = (Number)(obj.id.replace(/bonker/, ""));
}
//鼠标移走时执行
function clearColor(obj) {
    obj.style.backgroundColor = "";
}
//向下键 执行函数
function divNext() {
    try {
        if (bonkerLength != -1) {
            document.getElementById("bonker" + bonkerLength).style.backgroundColor = "";
        }
        bonkerLength++;
        if (bonkerLength == bonkerTotalLength) {
            bonkerLength = -1;
        }
        if (bonkerLength == -1) {
            textControl.value = bonkerData;
        } else {
            var obj = document.getElementById("bonker" + bonkerLength);
            obj.style.backgroundColor = "#EBEBEB";
            textControl.value = obj.innerHTML;
        }
    } catch (e) {
        return;
    }

}
//向上键 执行函数
function divPre() {
    try {
        if (bonkerLength != -1) {
            document.getElementById("bonker" + bonkerLength).style.backgroundColor = "";
        } else {
            bonkerLength = bonkerTotalLength;
            textControl.value = bonkerData;
        }
        bonkerLength--;
        if (bonkerLength == -1) {
            textControl.value = bonkerData;
        } else {
            var obj = document.getElementById("bonker" + bonkerLength);
            obj.style.backgroundColor = "#EBEBEB";
            textControl.value = obj.innerHTML;
        }
    } catch (e) {
        return;
    }

}
function bonkerFunction() {
    if (bonkerFun) {
        bonkerFun();
    }
}

 

 

 

 
                                 前台html文件
<!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>
    <title></title>
    <script src="bonker.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.onload = function () {
            init("myText", "AjaxHandler.ashx", btnclick);//调用封装的方法init(文本框id,后台ajax对应的地址,响应完执行的函数名(可选))
        }
        function btnclick() {
            alert(document.getElementById("myText").value);
        }
    </script>
</head>
<body>关键字:<input id="myText" type="text" />
    <input type="button"  value="搜索" id="btnSearch" onclick="btnclick();" />

</body>
</html>

 

         AjaxHandler.ashx文件内容
<%@ WebHandler Language="C#" class="AjaxHandler" %>
using System;
using System.Web;
using System.IO;
public class AjaxHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        StreamReader sr = new StreamReader(context.Request.InputStream);
        string arg = sr.ReadToEnd();
        context.Response.Write(arg+"1,ddfds ,dsfsdf,dsfsd,sdfsdf,ff,s,d,t,y");
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 

posted @ 2012-01-06 21:20  Bonker  阅读(849)  评论(0编辑  收藏  举报