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

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

1. 熱詞:html

       這些詞你能夠從後臺數據庫中取,能夠在cookies中讀取,也能夠在localStorage中讀取等,這些根據你的需求來定,這裏咱們把這些熱詞定義到一個json數據中,以下:數據庫

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

2. html代碼:json

<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代碼:cookie

    .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. 熱詞搜索:app

  1) 定義兩個成員變量:ide

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

  2)init():函數

    在這裏添加兩條監聽語句:this

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

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

     下一句不用說了,就是對鍵盤的監聽,由於咱們要用上下鍵控制下拉列表的選擇,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!這樣子一個可鼠標操做、鍵盤操做的搜索下拉列表就實現了,固然,這只是普通搜索熱詞搜索的一個簡單雛形,你們可縫縫補補把它作的更好!

相關文章
相關標籤/搜索