搜索输入框下拉列表热词搜索的实现

  咱们在百度时简单输入一些信息会在输入框的下面以列表的形式显示几条数据,这些都是与你所输入信息相关的热词,以提高用户的体验。下面咱们作下简单的实现: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!这样子一个可鼠标操做、键盘操做的搜索下拉列表就实现了,固然,这只是普通搜索热词搜索的一个简单雏形,你们可缝缝补补把它作的更好!

相关文章
相关标签/搜索