搜索輸入框下拉列表熱詞搜索的實現


  我們在百度時簡單輸入一些信息會在輸入框的下面以列表的形式顯示幾條數據,這些都是與你所輸入信息相關的熱詞,以提升用戶的體驗。下面我們做下簡單的實現:

1. 熱詞:

       這些詞你可以從后台數據庫中取,可以在cookies中讀取,也可以在localStorage中讀取等,這些根據你的需求來定,這里我們把這些熱詞定義到一個json數據中,如下:

var hotWords = [{name:"value1"},{name:"value2"},{name:"value3"}];

2. html代碼:

<div id="search">
    <input id="search_input" type="text" onclick="this.focus();this.value='';" onblur="showAndHide('hot_word','hide');"/> 
    <div id="search_button" onclick="search()"></div>
    <div class="menu" id="hot_word">
        <div class="menu2">
            <ul id="list"></ul>
        </div>
    </div>    
</div>

3. css代碼:

    .menu {
        position:relative;
        width:438px;
        z-index:2;
        background: #FFF;
        border:1px solid #000;
        margin-top:-20px;
        margin-left:20px;
        display:none;
        float:left;
    }
    .menu2 {
        position: absolute;
        left:0;
        top:0;
        width:100%;
        height:auto;
        overflow:hidden;
        z-index:1;
        float:left;
    }
    .Menu2 ul{margin:0;padding:0}
    .Menu2 ul li{
        width:100%;height:25px;line-height:25px;text-indent:15px;
        border-bottom:1px dashed #ccc;color:#666;cursor:pointer;
        float:left;    
    }

4. 熱詞搜索:

  1) 定義兩個成員變量:

var selectedLiId ; //被選中的li的id
var num = 9;       //下拉列表里可顯示的li的最大數目

  2)init():

    在這里添加兩條監聽語句:

searchImmediately();
document.addEventListener("keydown",function(e){onKeyDown(e);},false);

  searchImmediately()函數對輸入框輸入的信息不斷的監聽。

     下一句不用說了,就是對鍵盤的監聽,因為我們要用上下鍵控制下拉列表的選擇,enter鍵實現選中動作。

    3) 功能實現:

    searchImmediately()函數的代碼如下:

    function searchImmediately(){
        var element = document.getElementById("search_input");
        if("\v"=="v") {
              element.onpropertychange = inputChange;
        }else{
              element.addEventListener("input",inputChange,false);
        } 
function inputChange(){ if(element.value){ showHotWord(element.value); //建立下拉列表,函數會在下面說明 } }    }

  showHotWord()函數對用戶輸入的信息進行處理,並把得到的結果動態的建立li標簽並顯示在里面,具體的實現如下:

   function showHotWord(str){ //建立下拉列表
        str = $.trim(str);//去空格
        var list = window.document.getElementById("list");
        list.innerHTML = "";       
        var index = 1;
        for(var i = 0;i < hotWords.length;i++){
            var name = hotWords[i].name ;
            if(name.toLowerCase().indexOf(str.toLowerCase()) < 0) continue;
            if(index > num) break; //超過num定義的最大li數目就終止打印li
            var child = document.createElement("li");
            child.id = "word_" + index; //為每條li設置id
            
            child.onmousedown = function() {//監聽鼠標按下事件                                
          selectedLiId = null;
getValue('search_input',this); showAndHide('hot_word','hide'); } child.onmouseover=function(){//監聽鼠標滑上事件 selectedLiId = this.id; this.style.background="#F2F5EF"; //鼠標滑上改變li的顏色 } child.onmouseout=function(){//監聽鼠標滑出事件 this.style.background="";//鼠標滑上改回li的顏色 } child.innerHTML = name; list.appendChild(child); index++; } if(index == 1) { //沒搜到相關的熱詞,不顯示下拉列表 showAndHide('hot_word','hide'); eturn; } var wordDiv = window.document.getElementById("hot_word"); wordDiv.style.height = (index-1)*26+5+"px" ; //設置列表的高 showAndHide('hot_word','show'); }

showAndHide函數完成下拉列表的隱藏與顯示,完整代碼如下:

    function showAndHide(obj,types){ //下拉列表的顯示與隱藏
        var Layer=window.document.getElementById(obj);
        switch(types){
            case "show":
                Layer.style.display="block";
                break;
            case "hide":
                Layer.style.display="none";
                break;
        }
   }

   getValue函數是將選中的li的innerHTML值賦給input輸入框,並在輸入框中顯示,其完整代碼如下:

function getValue(id,obj){ //輸入框獲取下拉列表中被選中的li的數據 顯示在輸入框中
     var input=window.document.getElementById(id); 
     var li = window.document.getElementById(obj.id).innerHTML;
     input.value=li;
     search(); 
}

  其中search()為個人定義的搜索入口,對獲得的input值進行操作。功能實現就點到這里。

5. 鍵盤監聽的實現:

   上面在init函數里就已經把鍵盤的監聽加上去了,下面說下鍵盤的具體操作實現(只涉及到上下鍵和enter鍵)。代碼如下:

       function onKeyDown(e){ //鍵盤監聽器
           if (!e)  e = window.event;
           var keycode = e.which ? e.which : e.keyCode; console.log(keycode);
           switch (keycode){    
              case 13://enter鍵
                   var li = window.document.getElementById(selectedLiId);
                   getValue('search_input',li);
                   showAndHide('hot_word','hide');
                   break;
               case 38://上鍵
                   previousLi(selectedLiId);
                   break;
               case 40://下鍵
                   nextLi(selectedLiId);
                   break;
           }
      }
    
      function nextLi(id){ //下一條li
            if(id == null) id = "word_" + num;
            var strs = id.split('_');
            var idNum = parseInt(strs[1]);
            if(idNum == num) {
                idNum = 1;
            } else idNum++;
            selectedLiId = "word_" + idNum;
            window.document.getElementById(id).style.background="";
            window.document.getElementById(selectedLiId).style.background="#F2F5EF";
      }
    
      function previousLi(id){ //上一條li
            if(id == null) id = "word_" + num;
            var strs = id.split('_');
            var idNum = parseInt(strs[1]);
            if(idNum == 1) {
                idNum = num;
            } else idNum--;
            selectedLiId = "word_" + idNum;console.log(selectedLiId);
            window.document.getElementById(id).style.background="";
            window.document.getElementById(selectedLiId).style.background="#F2F5EF";
      }

 

  ok!這樣子一個可鼠標操作、鍵盤操作的搜索下拉列表就實現了,當然,這只是普通搜索熱詞搜索的一個簡單雛形,大家可縫縫補補把它做的更好!

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM