仿Google首页搜索自动补全

仿Google自动补全,实现细节:

后台是简单的servlet(其实就是负责后台处理数据交互的,没必要非跌用个struts...什么的)

传输介质:xml

使用jQuery js框架

功能实现:

如果在缓冲300ms内只输入一个字母,则开始与后台交互。

弹出检索匹配单词的层。可以通过方向键上下选择选项,被选择的高亮显示,颜色和Google的一模一样,并且键盘选择过程

中文本框动态赋值高亮单词,回车提交,ESC隐藏显示层,删除文本框中内容。

被鼠标选择的单词高亮显示,点击鼠标可以替换文本框内容,层自动消失。

backspace键删除后如果文本框不为空再次与服务器交互,检索。

回车提交,鼠标点按钮也可以提交。(最基本的)

xml文件用java提取数据库数据并生成。

基本就这样了。

功能也不复杂,不过这个功能网上的例子比较缺。

struts2里有自动补全的标签,不过如果检索中文还是需要再配置一下,但是这些标签,高度封装了Ajax,

不耽误看帖人的时间,页面源码:

jQueryAutoComplete.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery 自动完成功能(优化版)</title>
        <script type="text/javascript" src="js/jquery-1.2.6.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
    var highlightindex = -1;//表示当前高亮节点
    var timeoutId;
    $(document).ready(function() {
        var wordInput = $("#word");//文本框
        var wordInputOffset = wordInput.offset();//获得文本框位置
        $("#auto").hide().css("border", "1px black solid").css("position", "absolute")
                .css("top", wordInputOffset.top + wordInput.height() + 5 + "px")
                .css("left", wordInputOffset.left + "px").width(wordInput.width() + 3 + "px");
        wordInput.keyup(function(event) {
            //处理文本框中的键盘事件
            //如果输入字母,将文本框中最新信息发送给服务器
            var myEvent = event || window.event;
            var keyCode = myEvent.keyCode;//获得键值
            
            if (keyCode == 27) {
            var wordText = $("#word").val();
                autoHide();
                wordInput.text(wordText);
            }
            else {
                 if (keyCode >= 65 && keyCode <= 90 || keyCode == 8 || keyCode == 46) { //8对应退格键,46对应删除键
                    var wordText = $("#word").val();//获得文本框中的内容
                    var autoNode = $("#auto");
                    if (wordText != "") {
                        clearTimeout(timeoutId);//对上次未完成的延时操作进行取消
                        //延时操作,减少与服务器的交互次数,延时500ms,防止用户操作过快
                        timeoutId = setTimeout(function() {
                            $.post("AutoCompleteServlet", {word:wordText}, function(data) {//发送数据,第二项是属性名对应属性值
                                var jqueryObj = $(data);//将dom对象data转换成jQuery的对象
                                var wordNodes = jqueryObj.find("word");//找到所有word节点
                                autoNode.html("");
                                wordNodes.each(function(i) { //i是索引,用来给id赋值
                                   var wordNode = $(this);//获取单词内容
                                    var newDivNode = $("<div>").attr("id", i).css("backgroundColor", "white");
                                    newDivNode.html(wordNode.text()).appendTo(autoNode);//新建div节点,加入单词内容
                                    //增加鼠标进入事件,高亮节点
                                    newDivNode.mouseover(function() {
                                        //将原来高亮的节点取消高亮
                                        if (highlightindex != -1) {
                                            $("#auto").children("div").eq(highlightindex)
                                                    .css("backgroundColor", "white");
                                        }
                                        //记录新的高亮索引
                                        highlightindex = $(this).attr("id");
                                        $(this).css("backgroundColor", "#3366CC").css("cursor","pointer");
                                    });
                                    //增加鼠标移出事件,取消节点高亮
                                    newDivNode.mouseout(function() {
                                        if (keyCode == 13) {       //判断是否按下回车键
                                            //下拉框有高亮
                                            if (highlightindex != -1) {
                                                lightEventHide();
                                                highlightindex = -1;
                                            } else {
                                                alert("文本框中的[" + $("#word").val() + "]被提交了");
                                                autoHide();
                                                $("#word").get(0).blur();//让文本框失去焦点
                                            }
                                            //取消鼠标移出节点的高亮
                                            //$(this).css("backgroundColor", "white");
                                        }
                                    }
                                    );
                                        //增加鼠标点击事件,可以进行补全
                                        newDivNode.click(function() {
                                            //取出高亮节点的文本内容
                                            var comText = $(this).text();
                                            autoHide();
                                            highlightindex = -1;
                                            //文本框内容变为高亮节点内容
                                            $("#word").val(comText);
                                        });
                                    });
                                    //添加单词内容到弹出框
                                    if (wordNodes.length > 0) {
                                        autoNode.show();
                                    } else {
                                        autoNode.hide();
                                        highlightindex = -1;//弹出框隐藏,高亮节点索引设成-1
                                    }
                                }, "xml");
                            }, 300);
                        }
                    else
                    {
                        autoNode.hide();
                        highlightindex = -1;
                    }
                    } else if (keyCode == 38 || keyCode == 40) {   //判断是否输入的是向上38向下40按键
                        if (keyCode == 38) {
                            var autoNodes = $("#auto").children("div").css("background-color", "white");
                            if (highlightindex != -1) {
                                autoNodes.eq(highlightindex).css("background-color", "white");
                                highlightindex--;
                            } else {
                                lightEvent();
                                highlightindex = autoNodes.length - 1;
                            }
                            if (highlightindex == -1) {
                                highlightindex = autoNodes.length - 1;//如果改变索引值后index变成-1,则将索引值指向最后一个元素
                            }
                             lightEvent();
                             autoNodes.eq(highlightindex).css("backgroundColor", "#3366CC");
                        }
                        if (keyCode == 40) {
                            var autoNodes = $("#auto").children("div");
                            if (highlightindex != -1) {
                                autoNodes.eq(highlightindex).css("background-color", "white");
                            }
                            highlightindex++;
                            if (highlightindex == autoNodes.length) {
                                highlightindex = 0;//如果改变索引值等于最大长度,则将索引值指向第一个元素
                                
                            }
                             lightEvent();
                            autoNodes.eq(highlightindex).css("backgroundColor", "#3366CC");
                        }
                    } else if (keyCode == 13) {       //判断是否按下回车键
                        //下拉框有高亮
                        if (highlightindex != -1) {
                            lightEventHide();
                            highlightindex = -1;
                        } else {
                            alert("文本框中的[" + $("#word").val() + "]被提交了");
                            $("#auto").hide();
                            $("#word").get(0).blur();//让文本框失去焦点
                        }
                        //下拉框没有高亮
                    }
                }
            }
        )
            ;
            $("input[type='button']").click(function() {
                alert("文本框中的[" + $("#word").val() + "]被提交了");
            });
        });
function lightEventHide(){
        var comText = $("#auto").hide().children("div").eq(highlightindex).text();
                      $("#word").val(comText);
}
function lightEvent(){
        var comText = $("#auto").children("div").eq(highlightindex).text();
                      $("#word").val(comText);
}
function autoHide(){
        $("#auto").hide();
}
</script>
        
            <h3>
                <center>施杨 仿google自动补全(jQuery优化版)</center>
            </h3>
            <br />
            <table align="center">
            <tr><td>
            <input type="text" id="word" maxlength=2048 size=55 />
            <br/>
            <td></tr>
            <tr><td align="center">
            <input type="button" value="shiyang 搜索"/>
            </td></tr>
            </table>
            <br />
            <div id="auto"></div>
    </body>
</html>

截图:

自动补全(仿百度搜索框)

输入:a或b或c 即可看到效果

<!doctype html>
<html>
<style>
body {
    margin-left: 0px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
}
.auto_hidden {
    width:204px;border-top: 1px solid #333; 
    border-bottom: 1px solid #333; 
    border-left: 1px solid #333; 
    border-right: 1px solid #333;
    position:absolute;
    display:none;
}
.auto_show {
    width:204px;
    border-top: 1px solid #333; 
    border-bottom: 1px solid #333; 
    border-left: 1px solid #333; 
    border-right: 1px solid #333;
    position:absolute;
    z-index:9999; /* 设置对象的层叠顺序 */
    display:block;
}
.auto_onmouseover{
    color:#ffffff;
    background-color:highlight;
    width:100%;
}
.auto_onmouseout{
    color:#000000;
    width:100%;
    background-color:#ffffff;
}
</style>
<script language="javascript">
<!--
/*
通用: 自动补全(仿百度搜索框)
作者:nj-troy
时间:2010-11-101
*/
var $ = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
}
var Bind = function(object, fun) {
    return function() {
        return fun.apply(object, arguments);
    }
}
function AutoComplete(obj,autoObj,arr){
    this.obj=$(obj);        //输入框
    this.autoObj=$(autoObj);//DIV的根节点
    this.value_arr=arr;        //不要包含重复值
    this.index=-1;          //当前选中的DIV的索引
    this.search_value="";   //保存当前搜索的字符
}
AutoComplete.prototype={
    //初始化DIV的位置
    init: function(){
        this.autoObj.style.left = this.obj.offsetLeft + "px";
        this.autoObj.style.top  = this.obj.offsetTop + this.obj.offsetHeight + "px";
        this.autoObj.style.width= this.obj.offsetWidth - 2 + "px";//减去边框的长度2px    
    },
    //删除自动完成需要的所有DIV
    deleteDIV: function(){
        while(this.autoObj.hasChildNodes()){
            this.autoObj.removeChild(this.autoObj.firstChild);
        }
        this.autoObj.className="auto_hidden";
    },
    //设置值
    setValue: function(_this){
        return function(){
            _this.obj.value=this.seq;
            _this.autoObj.className="auto_hidden";
        }        
    },
    //模拟鼠标移动至DIV时,DIV高亮
    autoOnmouseover: function(_this,_div_index){
        return function(){
            _this.index=_div_index;
            var length = _this.autoObj.children.length;
            for(var j=0;j<length;j++){ 
                if(j!=_this.index ){        
                    _this.autoObj.childNodes[j].className='auto_onmouseout';
                }else{
                    _this.autoObj.childNodes[j].className='auto_onmouseover';
                }
            }
        }
    },
    //更改classname
    changeClassname: function(length){
        for(var i=0;i<length;i++){ 
            if(i!=this.index ){        
                this.autoObj.childNodes[i].className='auto_onmouseout';
            }else{
                this.autoObj.childNodes[i].className='auto_onmouseover';
                this.obj.value=this.autoObj.childNodes[i].seq;
            }
        }
    }
    ,
    //响应键盘
    pressKey: function(event){
        var length = this.autoObj.children.length;
        //光标键"↓"
        if(event.keyCode==40){
            ++this.index;
            if(this.index>length){ 
                this.index=0; 
            }else if(this.index==length){
                this.obj.value=this.search_value;
            }
            this.changeClassname(length);
        }
        //光标键"↑"
        else if(event.keyCode==38){
            this.index--;
            if(this.index<-1){
                this.index=length - 1;
            }else if(this.index==-1){
                this.obj.value=this.search_value;
            }
            this.changeClassname(length);
        }
        //回车键
        else if(event.keyCode==13){
            this.autoObj.className="auto_hidden";
            this.index=-1;
        }else{
            this.index=-1;
        }
    },
    //程序入口
    start: function(event){
        if(event.keyCode!=13&&event.keyCode!=38&&event.keyCode!=40){
            this.init();
            this.deleteDIV();
            this.search_value=this.obj.value;
            var valueArr=this.value_arr;
            valueArr.sort();
            if(this.obj.value.replace(/(^\s*)|(\s*$)/g,'')==""){ return; }//值为空,退出
            try{ var reg = new RegExp("(" + this.obj.value + ")","i");}
            catch (e){ return; }
            var div_index=0;//记录创建的DIV的索引
            for(var i=0;i<valueArr.length;i++){
                if(reg.test(valueArr[i])){
                    var div = document.createElement("div");
                    div.className="auto_onmouseout";
                    div.seq=valueArr[i];
                    div.onclick=this.setValue(this);
                    div.onmouseover=this.autoOnmouseover(this,div_index);
                    div.innerHTML=valueArr[i].replace(reg,"<strong>$1</strong>");//搜索到的字符粗体显示
                    this.autoObj.appendChild(div);
                    this.autoObj.className="auto_show";
                    div_index++;
                }
            }
        }
        this.pressKey(event);
        window.onresize=Bind(this,function(){this.init();});
    }
}
//-->
</script>
<body>
<h1 align="center">自动完成函数(Autocomplete Function)</h1>
    <div align="center"><input type="text" style="width:300px;height:20px;font-size:14pt;" id="o" onkeyup="autoComplete.start(event)"></div>
    <div class="auto_hidden" id="auto"><!--自动完成 DIV--></div>
<script>
    var autoComplete=new AutoComplete('o','auto',['b0','b12','b22','b3','b4','b5','b6','b7','b8','b2','abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);
</script>
</body>
</html>

 

posted @ 2015-10-23 10:26  星辰之力  阅读(1420)  评论(1编辑  收藏  举报