基于Proptotype的AutoComplete

在输入框内键入关键字,自动弹出相关搜索内容帮助,如baidu,google样的提示框
工具代码如下(重新排版,并加入注释):
var AutoComplete = Class.create({
    //ele:加入自动提示的输入框
    //func:创建提示框之前调用的函数,多为Ajax
    //options:选择项的颜色、父节点ID、选择某项后的回调函数,此参数可选
    initialize: function(ele,func,options){
        this.oInput = $(ele);
        this.getContent = func;
        this.oDiv = $(document.createElement('div'));
        this.visible = false;
        this.index = -1;
        this.count = 0;
        this.targetId = "";
        this.targetText = "";
        this.inputTextCount=0;
        this.oInputFocus = true;
        this.setDivStyle();
        this.options = this.setOptions(options);    
        this.appendDiv();
        Event.observe(this.oInput, 'blur', this.onBlur.bindAsEventListener(this));
        Event.observe(this.oInput, 'keydown', this.onKeyDown.bindAsEventListener(this));
        Event.observe(this.oInput, 'dblclick', this.onDblClick.bindAsEventListener(this));
        Event.observe(this.oInput, 'keyup', this.onKeyUp.bindAsEventListener(this));
    },
    //弹出层样式、属性
    setDivStyle:function(){
        var position = this.oInput.cumulativeOffset();
        this.oDiv.style.display = 'none';
        this.oDiv.style.position = 'absolute';
        this.oDiv.id = 'autoComplete';
        this.oDiv.style.width = this.oInput.getWidth() + "px";
        this.oDiv.style.left = position.left + "px";
        this.oDiv.style.top = position.top + this.oInput.getHeight() + "px";
        this.oDiv.style.border = "1px solid #cfcfcf";
        this.oDiv.style.zIndex = "100";
        this.oDiv.style.backgroundColor = "white";
    },
    //设置options参数
    setOptions:function(opt){
        var options = {
            hoverColor:'aqua',
            containerId:'',
            postAutoComplete:function(){}
        };
        Object.extend(options, opt || {});
        return options;
    },
    //每一项的样式、属性
    setItemStyle:function(ele, id, flag){
        ele.writeAttribute("dataid", id);
        ele.writeAttribute("dataflag", flag);
        ele.style.paddingLeft = "5px";
        ele.style.paddingRight = "5px";
        ele.style.paddingTop = "5px";
        ele.style.paddingBottom = "5px";
        ele.style.cursor = "default";
        ele.style.fontSize = "12px";
    },
    //将创建的提示DIV追加DOM中
    appendDiv:function(){
        if(this.options.containerId == '')
            document.body.appendChild(this.oDiv);
        else
            $(this.options.containerId).appendChild(this.oDiv);    
    },
    //
    finalize:function(){
        alert('not implement yet');
    },
    searchData:function(){
        this.clearItems();
        this.getContent(this.oInput.value);
    },
    show:function(){
        if(this.count > 0){
            Element.show(this.oDiv.id);
            this.visible = true;
        }
    },
    addItem:function(id, name, flag){
        var e = $(document.createElement('div'));
        this.setItemStyle(e, id, flag);
        this.addObserver(e);
        e.innerText = name;
        e.index = this.count;
        this.count = this.count + 1;
        this.oDiv.appendChild(e);
    },
    hide:function(){
        Element.hide(this.oDiv.id);
        this.clearItems();
        this.index = -1;
        this.visible = false;
        this.count = 0;
    },
    onBlur:function(){
        if(this.index == -1){
            this.hide();
        } else{
                
        }
    },
    onDblClick:function(){
        this.searchData();
    },
    onKeyDown:function(){
        if(this.visible){
            switch(event.keyCode){
                case Event.KEY_DOWN:
                    this.getNextItem();
                    Event.stop(event);
                    break;
                case Event.KEY_UP:
                    this.getPrevItem();
                    Event.stop(event);
                    break;
                case Event.KEY_RETURN:
                    this.selectItem();
                    Event.stop(event);
                    break;
            }
        }
    },
    onKeyUp:function(){
        if((event.keyCode >=65 && event.keyCode <= 90) ||
                (event.keyCode >=48 && event.keyCode <= 57) ||
                event.keyCode == 32){
            var _txt = this.oInput.value;
            this.inputTextCount = _txt.length;
            if(_txt.strip() != "" && this.inputTextCount > 0 && _txt != this.key) {
                this.key = this.oInput.value;
                this.searchData();
            }
        }
        if(!this.visible){
            if(event.keyCode == Event.KEY_DOWN && this.oInput.value != ''){
                this.searchData();
            }
        }
        if(event.keyCode == Event.KEY_BACKSPACE){
            if(this.oInput.value.blank()){
                this.hide();
                this.targetId = "";
            } else{
                var _txt = this.oInput.value;
	       this.inputTextCount = _txt.length;
	       if(_txt.strip() != "" && this.inputTextCount > 0 && _txt != this.key) {
	           this.key = this.oInput.value;
	           this.searchData();
	       }
            }
        }    
    },
    getNextItem:function(){
        var idx = (this.index == this.count - 1) ? (this.index = 0) : ++this.index;
        var ele = this.getCurrentItem(idx);
        this.render(ele);
    },
    getPrevItem:function(){
        var idx = (this.index == 0) ? (this.index = this.count - 1) : --this.index;
        var ele = this.getCurrentItem(idx);
        this.render(ele);
    },
    getCurrentItem:function(idx){
        var ele;
        $(this.oDiv.id).childElements().each(function(item){
            if(item.index == idx){
                ele = item;
                throw $break;
            }
        });
        return ele;
    },
    render:function(ele){
        $(this.oDiv.id).childElements().each(function(item){
            item.style.backgroundColor = 'white';
        });
        ele.style.backgroundColor = this.options.hoverColor;
        this.oInput.value = ele.innerText;
    },
    addObserver: function(element){
        Event.observe(element, "mouseover", this.onItemMouseOver.bindAsEventListener(this));
        Event.observe(element,"mouseout",this.onItemMouseOut.bindAsEventListener(this));
        Event.observe(element, "click", this.onItemClick.bindAsEventListener(this));
    },
    onItemMouseOver:function(){
        var ele = Event.findElement(event,'div');
        this.index = ele.index;
        $(this.oDiv.id).childElements().each(function(item){
            item.style.backgroundColor = 'white';
        });
        ele.style.backgroundColor = this.options.hoverColor;
        Event.stop(event);
    },
    onItemMouseOut:function(){
        var ele = Event.findElement(event,'div');
        this.index = -1;
        ele.style.backgroundColor = 'white';
        Event.stop(event);
    },
    onItemClick:function(){
        var ele = Event.findElement(event,'div');
        this.oInput.value = ele.innerText;
        this.targetflag = ele.readAttribute("dataflag");
        this.targetId = ele.readAttribute("dataid");
        this.targetName = ele.innerText;
        if(this.targetflag == "user") {
            chatUser(this.targetId, this.targetName);
        } else {
            chatGroup(this.targetId, this.targetName);
        }
        this.hide();
        this.options.postAutoComplete();
    },
    selectItem:function(){
        var ele;
        var children = $(this.oDiv.id).childElements();
        for(var i=0,len=children.length;i<len;++i){
            if(children[i].index == this.index){
                ele = children[i];
                break;
            }
        }
        if(!ele) return;
        this.oInput.value = ele.innerText;
        this.targetflag = ele.readAttribute("dataflag");
        this.targetId = ele.readAttribute("dataid");
        this.targetName = ele.innerText;
        if(this.targetflag == "user") {
            chatUser(this.targetId, this.targetName);
        } else {
            chatGroup(this.targetId, this.targetName);
        }
        this.hide();
        this.options.postAutoComplete();
    },
    clearItems:function(){
        while (this.oDiv.childNodes[0]){
            this.oDiv.removeChild(this.oDiv.childNodes[0]);  
        }
    },
    getId:function(){
        return this.oDiv.id;
    }
});


具体调用方法如下:
var complete = new AutoComplete("input_id",
function(val){
    new Ajax.Request(url, {method: 'post',parameters: {},
        onSuccess: function(rsp) {
            var jsonObj = rsp.responseText.evalJSON();
            for(var i=0,len=jsonObj.length;i<len;i++){
                //具体可以根据自己要求改写此方法
                complete.addItem(参数);
            }
            complete.show();
        },
        onFailure: function(){}
    });
});

你可能感兴趣的:(Ajax,Google,UP)