温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js模拟百度模糊搜索的实例

发布时间:2020-09-08 19:54:18 来源:脚本之家 阅读:139 作者:jingxian 栏目:web开发

废话不多说,直接上代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    *{
      margin:0;
      padding:0;
    }
    input{
      display:block;
      list-style:none;
    }
    html,body{
      color:#000;
      font-size:14px;
      font-family:'微软雅黑';
    }
    .box{
      margin:50px auto;
      width:300px;
    }
    .box input{
      padding:0 10px;
      width:278px;
      height:30px;
      border:1px solid green;
    }
    .box ul{
      display:none;
      border:1px solid green;
      border-top:none;
    }
    .box ul li{
      list-style:none;
      padding:0 10px;
      height:30px;
      line-height:30px;
      cursor:pointer;
    }
    .box ul li:hover{
      background:#eee;
    }
  </style>
</head>
<body>
  <div class='box'>
    <input type="text" id='searchInp'/>
    <ul id='searchBox'>
      <li>1111</li>
      <li>2222</li>
      <li>3333</li>
      <li>4444</li>
    </ul>
  </div>
  <script src='jquery.min.js'></script>
  <script>
    var searchModule = (function(){
      var $searchInp = $('#searchInp'),
        $searchBox = $('#searchBox');

      //向百度的服务器发送JSONP请求,把数据绑定到容器当中
      function bindHTML(){
        var searchKey = $searchInp.val();

        function callback(data){
          data = data['g'];
          var str = '';
          $.each(data,function(index,item){
            if(index<=3){
              str += '<li>'+item+'</li>'
            }
          })
          $searchBox.html(str).stop().slideDown(300);
        }

        $.ajax({
          url:"https://sp0.baidu.com/5a1Fazu8AA54nxGKo9WTAnF6hhy/su?wd="+searchKey,
          dataType:"jsonp",
          jsonp:'cb',
          success:callback

        })
      }

      //事件绑定和模块的入口
      function init(){
        //文本框获取焦点或者输入内容,判断当前文本框中是否有内容,有内容绑定数据,没有内容隐藏展示框
        $searchInp.on("focus keyup",function(){
          var val = $(this).val();
          if(val.length>0){
            bindHTML();
            return;
          }
          $searchBox.stop().slideUp(300);
        }).on('blur',function(){
          window.setTimeout(function(){
            $searchBox.stop().slideUp(300);
          },3000)
        })

        //给展示框中的li绑定方法
        $searchBox.on('click',function(e){
          var tar = e.target,
            tarTag = tar.tagName.toUpperCase(),
            $tar = $(tar);
          if(tarTag==="LI"){
            $searchInp.val($tar.html());
            $(this).stop().slideUp(300);
          }
        })

      }

      return {
        init:init
      }

    })()
    searchModule.init();
  </script>
</body>
</html>

以上这篇js模拟百度模糊搜索的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI