搜索提示框效果

搜索提示框效果

  • 首先写静态页面

    <div class="container">
        <!-- 搜索框 -->
        <input type="text" id="search" />
        <!-- 动态提示的数据框liebia -->
        <div id="alert">
            <ul></ul>
        </div>
    </div>
    
  • CSS样式

    * {
          
          
        margin: 0;
        padding: 0;
    }
    
    html,
    body {
          
          
        background: darkgray;
    }
    
    .container {
          
          
        position: absolute;
        left: 50%;
        top: 50px;
        transform: translateX(-50%);
    }
    
    #search {
          
          
        width: 300px;
        height: 50px;
        padding-left: 10px;
        border-radius: 5px;
        border: none;
        outline: none;
    }
    
    #alert {
          
          
        width: 312px;
        position: relative;
        left: -1px;
        display: none; /* 将ul列表隐藏 */
    }
    
    #alert > ul {
          
          
        list-style: none;
        margin: 0;
        padding: 0;
    }
    
    #alert > ul > li {
          
          
        border: 0.5px solid #000;
        height: 40px;
        line-height: 40px;
        padding-left: 10px;
        border-radius: 5px;
        background: #fff;
    }
    
    #alert > ul:last-child {
          
          
        border-bottom: 1px solid #000;
    }
    
  • JS代码

    var $search = $("#search");
    var $alert = $("#alert");
    var $alertUl = $("#alert>ul");
    
    // 清空列表的方法
    function clearUl() {
          
          
        $alertUl.empty();
    }
    
    $search
        .bind("input", function () {
          
          
        // 清空列表
        clearUl();
    
        // 获取到用户所输入的内容
        var value = $(this).val();
        // console.log(value);
    
        // 使用getJSON方法获取json数据
        $.getJSON("data/server4.json", function (data) {
          
          
            // console.log(data);
            // 获取到json数据中的name值
            $.each(data, function (input, obj) {
          
          
                // console.log(obj);
                var name = obj.name;
                // console.log(name);
    
                if (name.indexOf(value) >= 0) {
          
          
                    // 表示输入的内容在name中存在
                    var valueArr = obj.value;
                    // console.log(valueArr);
                    $.each(valueArr, function (input, text) {
          
          
                        // console.log(text);
                        // 将数据添加到HTML页面
                        $alertUl.append(`<li>${
            
            text}</li>`);
                    });
                }
            });
        });
    
        // 将ul列表显示出来
        $alert.css("display", "block");
    })
        .bind("blur", function () {
          
          
        $alert.css("display", "none");
    });
    
  • 实现效果

猜你喜欢

转载自blog.csdn.net/Cool_breeze_/article/details/108408097