模糊搜索功能在工作中应用广泛,并且很实用,自己写了一个方法,以后用到的时候可以直接拿来用了!

实现的搜索功能:

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

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

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

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

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

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

先来预览一下效果吧!

列表中包含的列表项有:

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

点击链接预览模糊搜索功能

http://sandbox.runjs.cn/show/kwxlptbl

下面就开始实现功能啦!

一、首先,引入jquery文件

<script type="text/javascript" src="js/jquery/jquery-3.2.1.min.js"></script>

二、html部分 

<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> 

三、编写样式 

<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> 

此时的页面:

四、使用js、jquery实现模糊搜索功能

<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>

此时的页面

需要注意的地方:

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

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

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

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

还能在线调试哦!

http://runjs.cn/code/kwxlptbl

如果对您有帮助,记得点赞哦!需要你的支持与鼓励,同时也欢迎您留下宝贵意见!

js、jquery实现模糊搜索功能的更多相关文章

  1. js、jquery实现列表模糊搜索功能

    实现的搜索功能: 1. 可以匹配输入的字符串找出列表中匹配的项,列表框的高度跟随搜索出的列表项的多少改变 2. 可以点击某一项进行选中列表项 3. 可以按下上.下.回车键来控制列表项 4. 按下回车键 ...

  2. js/jQuery实现类似百度搜索功能

    一.页面代码:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www. ...

  3. Jquery.LazyLoad.js实现图片延迟加载功能

    从网上下载来的版本多多少少都有些BUG,尤其是加载后在IE6和IE7下图片闪动是个大问题,在网上查了很久,也没有找到相关的解决方案.没解决方案,就得发挥咱DIY的精神,自己想法解决,分析了BUG,理了 ...

  4. ztree树的模糊搜索功能

    在做机场项目的时候,业务为一个input框,点击的时候出现一个下拉树,这个下拉树是所有的设备,由于设备太多,加上分了区域,为了更好的用户体验,设计一个模糊搜索的功能,方便用户进行选择 具体实现过程如下 ...

  5. js/jquery/html前端开发常用到代码片段

    1.IE条件注释 条件注释简介 IE中的条件注释(Conditional comments)对IE的版本和IE非IE有优秀的区分能力,是WEB设计中常用的hack方法.条件注释只能用于IE5以上,IE ...

  6. JS Jquery去除数组重复元素

    js jquery去除数组中的重复元素 第一种:$.unique() 第二种: for(var i = 0,len = totalArray_line.length;i < len;i++) { ...

  7. js,jquery概念理解

    js,jquery都是一种脚本语言,编写代码,实现页面的dom操作,特效等功能. 区别: 1.jquery"写的更少,做的更多"; 2.使用jquery需要导入jquery文件. ...

  8. ASP.NET MVC 4 RC的JS/CSS打包压缩功能 (转载)

    ASP.NET MVC 4 RC的JS/CSS打包压缩功能 打包(Bundling)及压缩(Minification)指的是将多个js文件或css文件打包成单一文件并压缩的做法,如此可减少浏览器需下载 ...

  9. jquery实现菜单功能(单击展开或者关闭)-一般应用于后台

    <!doctype html> <html> <head> <meta charset="gb2312"> <title> ...

随机推荐

  1. 北京Python筛选过程中应注意什么

    计算机初级爱好者普遍喜欢Python,因为Python干净利索,简单直接.它编写代码的速度非常的快,而且非常注重代码的可读性,非常适合多人参与的项目.很多人选择了培训,那么北京Python培训筛选过程 ...

  2. C#保留小数位数的方法

    1.System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();provi ...

  3. 100000个嵌入式学习者遇到的PING不通问题,我们使用这一个视频就解决了,牛!

    在10多年的售后答疑历程中,我们每天都会遇到开发板.windows,ubuntu三者之间的PING通问题,常常中断手头中的工作去解决这类问题,甚至跟客户远程协助,颇耗时间与精力,在热心网友.答疑助手们 ...

  4. .net core 同时实现网站管理员后台、会员、WebApi登录及权限控制

    我们在开网站信息系统时,常常有这样几个角色,如后台的管理员,前台的会员,以及我们各种应用的WebAPI 都需要进行登录操作及权限控制,那么在.net core如何进行设计呢. 首先我使用的是.net ...

  5. 数据库中File权限的危害

    The FILE privilege gives you permission to read and write files on the server host using the LOAD DA ...

  6. Entity Framework Core 使用HiLo生成主键

    #cnblogs_post_body.cnblogs-markdown p img { max-width: 95%; } HiLo是在NHiernate中生成主键的一种方式,不过现在我们可以在Ent ...

  7. OC语言的Block与Protocol(协议)

    Block ● Block封装了一段代码,可以在任何时候执⾏行 ● Block可以作为函数参数或者函数的返回值,⽽而其本⾝身又可以带输⼊入参数或返回值. ● 苹果官⽅方建议尽量多⽤用block.在多线 ...

  8. 解决WebSocket兼容ie浏览器版本问题

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7942323.html 在使用Netty进行WebSocket开发时,测试发现:ie 11系列个别低版本连接W ...

  9. [ 面试没回答上的问题2]IOS上给body绑定click事件的bug

    面试被问到ios上的bug,自己提到绑定click事件的bug,但是并没有把问题讲的很清楚,这里再清理一下思路. 这个bug只在IOS上有,包括ihone,ipad,由于ios浏览器都用的safari ...

  10. Servlet之会话(Session)以及会话追踪技术(Cookie),(URL重写)和(隐藏表单域)

    Session 什么是会话? 会话: Web应用中的会话 指的是一个客户端浏览器与Web服务器之间连续发生的一系列请求和响应的过程 会话状态: Web服务器和浏览器在会话的过程中产生的状态信息 作用: ...