模糊搜索框(H5),兼容安卓和ios(令人头大的ios输入法)

项目里要可以实现,按照模糊,于是从jq22网站找到一个代码,效果如图:

具体的html代码:(复制,需要引入jq相关的支持文件)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>模糊搜索</title>
    <script id="jquery_183" type="text/javascript" class="library" src="jquery-1.11.1.min.js"></script>

    <style>
        * {
        padding: 0;
        margin: 0;
    }
    body {
        background: #fff;
    }
    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(http://sandbox.runjs.cn/uploads/rs/382/gzpur0hb/select-default.png) no-repeat; 
        opacity: 1; 
        width: 15px; 
        height: 8px;
        position: absolute;
        top: 10px;
        right: 125px;
    }
    .picture_click:hover {
        background-image: url(http://sandbox.runjs.cn/uploads/rs/382/gzpur0hb/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>
    <script>
    //初始化下拉框
    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>
    </head>
    <body>
        <div id="container">
            <h2>模糊搜索</h2>
            <div id="cityContainer" class="selectContainer">
                <label>城市:</label>
                <input type="text" placeholder="请输入城市名称" list="listps" 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>
</html>

修改的第一版:按照名称进行模糊查询:

搜索效果:

添加,每行的颜色渐变:

//文本框中输入的字符串
var searchVal = $(that).val();
showList = [];
//将和所输入的字符串匹配的项存入showList
//将匹配项显示,不匹配项隐藏
$.each(listArr, function (index, item) {
console.log("item" + item.eleName);
if (item.eleName.indexOf(searchVal) != -1) {
item.ele.style.display = "block";
showList.push(item.ele);
} else {
item.ele.style.display = 'none';
}
})
                   
//设置当前项的背景色及位置
$.each(showList, function (index, item) {
 // console.log("index===" + index % 2)
  if (index % 2 == 1) {
     item.style.background = "#d6e4ff";
     } else {
       item.style.background = "#ffffff";
   }
 })

 

跟ios浏览器显示的较劲,首先区别于安卓微信的x5浏览器,苹果手机的微信浏览器不支持,keyup,的事件,输入内容后,无法正常检索,实现模糊查询的功能,

于是上网找到了input的方法;

inupt方法,可以正常触发搜索框内容改变的事件,但是在ios输入法,输入字符串成效果会先把拼音加载到输入框,导致输入框出现乱码;解决方法,加入了compositionstart,compositionend的方法,这个东西相当于一个开关,当你输入完成后,给搜索框一个结果,现在可以检索了,就如同一个钥匙,把门开开后,你就不FQ,就可以光明正大的走出来了。代码如下:

 var node = this;
    var inputLock = false;
    node.addEventListener('compositionstart', function (e) {
        inputLock = true;
        //console.log("satart" + e.data)
    })

    node.addEventListener('compositionupdate', function (e) {
       // console.log("update"+e.data)
    })
    node.addEventListener('compositionend', function (e) {
        inputLock = false;
      //  console.log("end" + e.data)
    })
   // console.log("inputlock"+inputLock)
    if (!inputLock) {
       bind_name = 'input';
    }
    //var bind_name = 'propertychange';
    
    $(this).bind(bind_name, function (e) {
 //查询内容
  xxx
})

 

  因为涉及到多个页面的使用和判断,这里就不把详细的代码帖出来了,最原始的代码给了大家,各个坑也给大家填了不少,其他就看自己的需求了。

 

  

 

posted @ 2018-07-26 16:17  西平sir  阅读(1002)  评论(0编辑  收藏  举报