js仿baidu google 實用的文本框內容自動完成效果

<!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>

<meta http-equiv="content-type" content="text/html;charset=gb2312">

<!--把下面代碼加到<head>與</head>之間-->

<style type="text/css">

html{overflow:-moz-scrollbars-vertical;}

body{padding:0;margin:0;font:12px/1.5 Tahoma,Helvetica,Arial,sans-serif;}

body,h1,p,blockquote,dl,dt,dd,ul,ol,li,input{margin:0;padding:0;}

button,input,select,textarea {font:12px/1.5 tahoma,arial,simsun,sans-serif;}

button,input,select,textarea{font-size:100%;}

a{text-decoration:none;}

a:hover{text-decoration:underline;}

#wrap{width:650px;margin:0 auto;}

.txt{width:210px;height:25px;border:1px solid #ccc;line-height:25px;padding:0 5px;}

.autoDis{border:1px solid #999;position:absolute;overflow:hidden;}

.autoDis p{line-height:25px;cursor:default;padding:0 5px;}

.autoDis li{line-height:25px;cursor:default;padding:0 5px;background-color:#fff;}

.autoDis .cur{background:#ccc;}

</style>

</head>

<body>

<!--把下面代碼加到<body>與</body>之間-->

<div id="wrap">

 <p>提示:可以輸入“1”開頭的</p>

 <input id="autoCom" type="text" class="txt">

 <input id="autoC" type="text" class="txt">

</div>

<script type="text/javascript">

(autoComplete={

    pop_len:10,

    pop_cn:'autoDis',

    hover_cn:'cur',

    source:'13612345564|13825646464|13412236054|13012348564|13012345564|13012365564|彭小|王達|李相公|周歡歡'.split('|'),

    init:function(){

        this.setDom();

        return this;

    },

    bind:function(x){

        if(x.getAttribute('type') != 'text' || x.nodeName != 'INPUT')

            return null;

        var self = this;

        x.onkeyup = function(e){

            e = e || window.event;

            var lis = self.pop.getElementsByTagName('li'),lens = self.pop.getElementsByTagName('li').length,n=lens,temp;

            if(e.keyCode == 38){                                        //鍵盤up鍵被按下

                if(self.pop.style.display != 'none'){

                    for(var i=0;i<lens;i++){                            //遍歷結果數據,判斷是否被選中

                        if(lis[i].className)

                            temp = i;

                        else

                            n--;

                    }

                    if(n==0){                                                //如果沒有被選中的li元素,則選中最後一個

                        lis[lens-1].className = self.hover_cn;

                        this.value = lis[lens-1].innerHTML;

                    }else{                                                    //如果有被選中的元素,則選擇上一個元素並賦值給input

                        if(lis[temp] == lis[0]){                        //如果選中的元素是第一個孩子節點則跳到最後一個選中

                            lis[lens-1].className = self.hover_cn;

                            this.value = lis[lens-1].innerHTML;

                            lis[temp].className = '';

                        }else{                                                

                            lis[temp-1].className = self.hover_cn;

                            this.value = lis[temp-1].innerHTML;

                            lis[temp].className = '';

                        }

                    }

                }else                                                //如果彈出層沒有顯示則執行插入操作,並顯示彈出層

                    self.insert(this);

            }else if(e.keyCode == 40){                     //down鍵被按下,原理同up鍵

                if(self.pop.style.display != 'none'){

                    for(var i=0;i<lens;i++){

                        if(lis[i].className)

                            temp = i;

                        else

                            n--;

                    }

                    if(n==0){

                        lis[0].className = self.hover_cn;

                        this.value = lis[0].innerHTML;

                    }else{

                        if(lis[temp] == lis[lens-1]){

                            lis[0].className = self.hover_cn;

                            this.value = lis[0].innerHTML;

                            lis[temp].className = '';

                        }else{

                            lis[temp+1].className = self.hover_cn;

                            this.value = lis[temp+1].innerHTML;

                            lis[temp].className = '';

                        }

                    }

                }else

                    self.insert(this);

            }else                                    //如果按下的鍵既不是up又不是down那麼直接去匹配數據並插入

                self.insert(this);

        };

        x.onblur = function(){                //這個延遲處理是因爲如果失去焦點的時候是點擊選中數據的時候會發現先無法觸發點擊事件

            setTimeout(function(){self.pop.style.display='none';},300);

        };

        return this;

    },

    setDom:function(){

        var self = this;

        var dom = document.createElement('div'),frame=document.createElement('iframe'),ul=document.createElement('ul');

        document.body.appendChild(dom);

        with(frame){                                    //用來在ie6下遮住select元素

            setAttribute('frameborder','0');

            setAttribute('scrolling','no');

            style.cssText='z-index:-1;position:absolute;left:0;top:0;'

        }

        with(dom){                                        //對彈出層li元素綁定onmouseover,onmouseover

            className = this.pop_cn;

            appendChild(frame);

            appendChild(ul);

            onmouseover  = function(e){            //在li元素還沒有加載的時候就綁定這個方法,通過判斷target是否是li元素進行處理

                e = e || window.event;

                var target = e.srcElement || e.target;

                if(target.tagName == 'LI'){            //添加樣式前先把所有的li樣式去掉,這裏用的是一種偷懶的方式,沒有單獨寫removeClass方法

                    for(var i=0,lis=self.pop.getElementsByTagName('li');i<lis.length;i++)

                        lis[i].className = '';

                    target.className=self.hover_cn;        //也沒有寫addClass方法,直接賦值了

                }

            };

            onmouseout = function(e){

                e = e || window.event;

                var target = e.srcElement || e.target;

                if(target.tagName == 'LI')

                    target.className='';

            };

        }

        this.pop = dom;

    },

    insert:function(self){

        var bak = [],s,li=[],left=0,top=0,val=self.value;

        for(var i=0,leng=this.source.length;i<leng;i++){         //判斷input的數據是否與數據源裏的數據一致

            if(!!val&&val.length<=this.source[i].length&& this.source[i].substr(0,val.length) == val){

                bak.push(this.source[i]);

            }

        }

        if(bak.length == 0){                                                    //如果沒有匹配的數據則隱藏彈出層

            this.pop.style.display='none';

            return false;

        }//這個彈出層定位方法之前也是用循環offsetParent,但發現ie跟ff下差別很大(可能是使用方式不當),所以改用這個getBoundingClientRect

        left=self.getBoundingClientRect().left+document.documentElement.scrollLeft;

        top=self.getBoundingClientRect().top+document.documentElement.scrollTop+self.offsetHeight;

        with(this.pop){

            style.cssText = 'width:'+self.offsetWidth+'px;'+'position:absolute;left:'+left+'px;top:'+top+'px;display:none;';

            getElementsByTagName('iframe')[0].setAttribute('width',self.offsetWidth);

            getElementsByTagName('iframe')[0].setAttribute('height',self.offsetHeight);

            onclick = function(e){

                e = e || window.event;

                var target = e.srcElement || e.target;

                if(target.tagName == 'LI')

                    self.value = target.innerHTML;

                this.style.display='none';

            };

        }

        s = bak.length>this.pop_len?this.pop_len:bak.length;

        for(var i=0;i<s;i++)

            li.push( '<li>' + bak[i] +'</li>');

        this.pop.getElementsByTagName('ul')[0].innerHTML = li.join('');

        this.pop.style.display='block';

    }

}).init().bind(document.getElementById('autoCom')).bind(document.getElementById('autoC'));

</script>

</body>

</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章