联想输入框(本地搜索)

 场景:(少量数据)把所有数据查询出来存到变量里,进行本地搜索

优点:查询速度快

缺点:数据有可能,不能实时

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>联想输入框</title>
  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .association-input{
       position: relative;
        width: 200px;
    }
    .association-input input{
      width: 200px;
      height: 30px;
      border: 1px solid #bababa;
      border-radius: 2px;
      padding: 0 5px;
      box-sizing: border-box;
      /*box-shadow: 2px 2px 8px #b9b9b9 , -2px 2px 8px #b9b9b9;*/
    }
    .association-input ul {
      display: none;
      position: absolute;
      max-height: 200px;
      overflow: hidden;
      overflow-y: auto;
      left: 0;
      right: 0;
      margin-left:0;
      background-color: #fff;
      border: 1px solid #bababa;
      border-top: none;
      box-shadow: 2px 2px 8px #b9b9b9 , -2px 2px 8px #b9b9b9;
    }
    .association-input ul li{
      display: inline-block;
      width: 100%;
      line-height: 30px;
      list-style-type:none;
      text-align:left;
      padding-left: 20px;
      cursor:pointer;
    }
    .association-input ul li:hover{
      background-color: #f8f8f8;
    }
  </style>
</head>
<body>
<div class="association-input">
  <input type="text" id="association">
  <ul id="association-select">
  </ul>
</div>
<script>

  var arr=[
    {id:'1',name:'张三'},
    {id:'2',name:'李四'},
    {id:'3',name:'王二麻子'}
  ];


  if(/msie/i.test(navigator.userAgent)) {   //ie浏览器
    document.getElementById('association').attachEvent("onpropertychange", handle);
  }
  else {//非浏览器
    document.getElementById('association').addEventListener("input", handle, false);
  }

  function handle() {
    if(document.getElementById('association').value==''){
      document.getElementById('association-select').style.display ='none';
    }else {
      var val = document.getElementById('association').value;
      search(val)
    }
  }

  var oUl = document.getElementById("association-select");
  var aLi = oUl.getElementsByTagName("li");
  oUl.onclick = function(ev){
    var ev = ev || window.event;
    var target = ev.target || ev.srcElement;
    if(target.nodeName.toLowerCase() == "li"){
      document.getElementById('association').value=target.innerHTML;
      document.getElementById('association-select').style.display ='none';
    }
  };
  function search(val) {
    document.getElementById('association-select').innerHTML='';
     var html='';
      for (var i=0;i<arr.length;i++){
        if((arr[i].name).indexOf(val)>-1){
          document.getElementById('association-select').style.display ='block';
          var li = document.createElement("li");
          li.setAttribute("id", arr[i].id);
          li.innerHTML=arr[i].name;
          document.getElementById('association-select').appendChild(li)
        }
      }
  }
</script>
</body>
</html>

 

posted @ 2019-03-27 10:27  (⊙o⊙)买噶  阅读(294)  评论(0编辑  收藏  举报