zoukankan      html  css  js  c++  java
  • js、jquery实现列表模糊搜索功能

    实现的搜索功能:

    1. 可以匹配输入的字符串找出列表中匹配的项,列表框的高度跟随搜索出的列表项的多少改变

    2. 可以点击某一项进行选中列表项

    3. 可以按下上、下、回车键来控制列表项

    4. 按下回车键时则会选中列表项

    5. 点击文本框中的下拉键头时会切换下拉框的显示/隐藏

    6. 点击文本框外部时自动隐藏下拉框

    先来预览一下效果吧! 

    列表中包含的列表项有: 

    北京、上海、杭州、安庆、大兴安岭、安阳、广州、贵阳、哈尔滨、合肥、邯郸、呼伦贝尔、淮南、黄山、济南、济宁、嘉兴、南昌、南通、南宁、南京
    在预览时需要输入匹配以上项目的文字,以便更好的预览效果 

     具体的代码实现

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>js、jquery实现列表模糊搜索功能</title>
     <script src="https://lib.baomitu.com/jquery/3.4.1/jquery.js"></script>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }
        h2 {
            margin-bottom: 20px;
        }
        #container {
            width: 500px;
            text-align: center;
            margin: 0 auto;
            font-family: "微软雅黑";
            margin-top: 50px;
        }
        .selectContainer {
            position: relative;
        }
        .selectInput {
            width: 200px;
            height: 25px;
            border-style: none;
            border: 1px solid #999;
            border-radius: 3px;
            padding: 0 3px;
        }
        .picture_click {
            background: url(img/select-default.png) no-repeat; 
            opacity: 1; 
            width: 15px; 
            height: 8px;
            position: absolute;
            top: 10px;
            right: 125px;
        }
        .picture_click:hover {
            background-image: url(img/select-hover.png);
        }
        .selectList {
            width: 206px;
            height: 212px;
            overflow-y: scroll;
            text-align: left;
            margin: 0 172px;
            border: 1px solid #999;
            display: none;
            position: relative;
        }
        .selectList div {
            cursor: pointer;
        }
    </style>
    </head>
    <body>
    <div id="container">
        <h2>模糊搜索</h2>
        <div id="cityContainer" class="selectContainer">
            <label>城市:</label>
            <input type="text" placeholder="请输入城市名称" list="cityList" class="selectInput" name="cityName" id="cityName" value="" onfocus="fuzzySearch.call(this)" />
            <div class="picture_click dropDowns" style=""></div>
            <div id="cityList" class="selectList">
                <div id="001">北京</div>
                <div id="002">上海</div>
                <div id="003">杭州</div>
                <div id="004">安庆</div>
                <div id="005">大兴安岭</div>
                <div id="006">安阳</div>
                <div id="007">广州</div>
                <div id="008">贵阳</div>
                <div id="009">哈尔滨</div>
                <div id="010">合肥</div>
                <div id="011">邯郸</div>
                <div id="012">呼伦贝尔</div>
                <div id="013">淮南</div>
                <div id="014">黄山</div>
                <div id="015">济南</div>
                <div id="016">济宁</div>
                <div id="017">嘉兴</div>
                <div id="018">南昌</div>
                <div id="019">南通</div>
                <div id="020">南宁</div>
                <div id="021">南京</div>
            </div>
        </div>
    </div>
    </body>
    <script type="text/javascript">
        //初始化下拉框
        initSearchInput();
    
        function fuzzySearch(e) {
            var that = this;
            //获取列表的ID
            var listId = $(this).attr("list");
            //列表
            var list = $('#' + listId + ' div');
            //列表项数组  包列表项的id、内容、元素
            var listArr = [];
            //遍历列表,将列表信息存入listArr中
            $.each(list, function(index, item){
                var obj = {'eleId': item.getAttribute('id'), 'eleName': item.innerHTML, 'ele': item};
                listArr.push(obj);
            })
            
            //current用来记录当前元素的索引值
            var current = 0;
            //showList为列表中和所输入的字符串匹配的项
            var showList = [];
            //为文本框绑定键盘引起事件
            $(this).keyup(function(e){
                //如果输入空格自动删除
                this.value=this.value.replace(' ','');
                //列表框显示
                $('#' + listId).show();
                if(e.keyCode == 38) {
                    //up
                    console.log('up');
                    current --;
                    if(current <= 0) {
                        current = 0;
                    }
                    console.log(current);
                }else if(e.keyCode == 40) {
                    //down
                    console.log('down');
                    current ++;
                    if(current >= showList.length) {
                        current = showList.length -1;
                    }
                    console.log(current);
    
                }else if(e.keyCode == 13) {
                    //enter
                    console.log('enter');
                    //如果按下回车,将此列表项的内容填充到文本框中
                    $(that).val(showList[current].innerHTML);
                    //下拉框隐藏
                    $('#' + listId).hide();
                }else {
                    //other
                    console.log('other');
                    //文本框中输入的字符串
                    var searchVal = $(that).val();
                    showList = [];
                    //将和所输入的字符串匹配的项存入showList
                    //将匹配项显示,不匹配项隐藏
                    $.each(listArr, function(index, item){
                        if(item.eleName.indexOf(searchVal) != -1) {
                            item.ele.style.display = "block";
                            showList.push(item.ele);
                        }else {
                            item.ele.style.display = 'none';
                        }
                    })
                    console.log(showList);
                    current = 0;
                }
                //设置当前项的背景色及位置
                $.each(showList, function(index, item){
                    if(index == current) {
                        item.style.background = "#eee";
                        $('#' + listId).scrollTop(item.offsetTop);
                    }else {
                        item.style.background = "";
                    }
                })
                //设置下拉框的高度
                //212为列表框的最大高度
                if(212 > $('#' + listId + ' div').eq(0).height() * showList.length) {
                    $('#' + listId).height($('#' + listId + ' div').eq(0).height() * showList.length);
                }else {
                    $('#' + listId).height(212);
                }
            })
        }
    
        function initSearchInput() {
            //给下拉箭头绑定点击事件  点击下拉箭头显示/隐藏对应的列表
            //输入框的类名为selectInput
            //下拉箭头的类名为picture_click、dropDowns
            //下拉列表的类名为selectList
            for(var i = 0; i < $('.picture_click').length; i++) {
                 $('.picture_click').eq(i).click(function(){
                     $(this).parent().find('.selectList').toggle();
                 })
            }
            //为列表中的每一项绑定鼠标经过事件
            $('.selectList div').mouseenter(function(){
                $(this).css("background", "#eee").siblings().css("background", "");
            });
            //为列表中的每一项绑定单击事件
            $('.selectList div').click(function(){
                //文本框为选中项的值
                $(this).parent().parent().find('.selectInput').val($(this).html());
                //下拉框隐藏
                $(this).parent().hide();
            });        
    
            //点击下拉框外部的时候使下拉框隐藏
            var dropDowns = document.getElementsByClassName('dropDowns');
            var selectList = document.getElementsByClassName('selectList');
            document.body.onclick = function(e){
                e = e || window.event;
                var target = e.target || e.srcElement;
                for(var i = 0; i < dropDowns.length; i++) {
                    if(target != dropDowns[i] && target != selectList[i]){
                        selectList[i].style.display = 'none';
                    }
                }
            }
        }
    
    </script>
    </html>

    需要注意的地方:

    1. 使用此方法时,需要给输入框加类名selectInput,给下拉剪头加类名picture_click、dropDowns,给列表框加类名selectList;

    2. 输入框需要有list属性,list属性对应的值为列表框的id值

    3. 需要给文本框绑定事件,onfocus="fuzzySearch.call(this)",(由于自定义的函数中,this指向的是window,所以需要通过call方法改变this指向,即指向该文本框,以便在方法中使用)

    4. 在实现搜索功能的过程中,遇到一点小问题,就是在获取列表项的offersetTop时,获取的是28,找不出原因,最终通过查阅相关资料终于解决,即想要获取子元素的offsetTop,则需要给父元素设置相对定位,才能获取到正确的offsetTop。

     
  • 相关阅读:
    Python中的魔法方法【技能突破】
    Python简明教程:面向对象【新手必学】
    No such file or directory
    LaTeX Error: File ''picins.sty'' not Found.
    GCC编译过程中的各种not declared in this scope
    20.有效的括号-力扣
    c++标准库bitset文件
    c++标准库windows.h文件
    warning: control reaches end of non-void function
    c++标准库iostream文件
  • 原文地址:https://www.cnblogs.com/mjtabu/p/11975066.html
Copyright © 2011-2022 走看看