jQuery实现模糊搜索效果

使用jQuery中:contains选择器实现模糊搜索、匹配关键字效果。

  • 南京理工
  • 华师大
  • 合工大
  • 哈工大
  • 复旦
  • 清华
  • 同济
  • 南开
  • 中山
  • 南航
  • 武汉
body {
	background-color:#f5f5f5;
}
.warp {
	width:50%;
	margin:0 auto;
}
/*清除input默认样式*/
input {
	border:0;
	background-color:transparent;
}
/*搜索栏*/
.search_box {
	width:60%;
	height:32px;
	box-sizing:border-box;
	box-shadow:1px 1px 4px #e2e2e2;
	padding:0 10px;
	border:1px solid #e2e2e2;
	border-radius:4px;
	background-color:#f5f5f5;
	margin:50px auto 20px auto;
}
.search_box input {
	width:80%;
	height:30px;
	line-height:30px;
	font-size:15px;
	color:#8c8282;
}
.search_box .search_icon {
	float:right;
	display:inline-block;
	width:24px;
	height:24px;
	background:url("img/search.png") no-repeat center center;
	background-size:cover;
	margin-top:3px;
}
/*搜索内容*/
.search_content {
	width:60%;
	margin:0 auto;
	background-color:#fff;
	border-radius:8px;
}
.search_content ul {
	padding-left:0;
}
.search_content li {
	width:90%;
	margin:0 auto;
	height:40px;
	line-height:40px;
	box-sizing:border-box;
	border-bottom:.4px solid #e2e2e2;
	list-style:none;
}
.search_content li:last-child {
	border-bottom:0;
}
.search_content li a {
	color:#8c8282;
}
$(function() {
    var search_input = $(".search_box input"),
        search_content = $(".search_content");
    $(search_input).on("keyup", function() {
        if (search_input.val() == '') {
            $(search_content).show();
        }
        $(".search_content li:contains(" + search_input.val().trim() + ")").show();
        $(".search_content li:not(:contains(" + search_input.val().trim() + "))").hide();


        //第二中方法
        //$(".search_content li").hide().filter(":contains("+ search_input.val().trim() +")").show();
    });
});

搜索功能思路: 当触发 keyup 键盘松开事件时,判断 input 输入框中的内容是不是 li 标签里包含的内容,包含则该  li 标签显示,不包含 则该 li 标签隐藏。

开发步骤:

1.使用 keyup 键盘松开事件,当键盘松开时触发以下内容。

2. 先获取 input 输入框中的内容。

3. 利用 jQuery 中 :contains 选择器判断 li 标签中的内容是否包含 input 输入框中的内容。

4.如果包含则该 li 标签显示,否则 则隐藏。

你可能感兴趣的:(js知识,前端开发知识)