利用css实现搜索过滤

时间:2023-03-09 20:13:26
利用css实现搜索过滤

无意中找到一种利用css就可实现的搜索过滤的方法,不得不说看了代码之后确实被惊艳到了,亏我之前面试还因为做这个功能做太慢而拖了后腿。在此记录下代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
[type=search]{
width: 160px;
padding: 5px;
}
label{
display: block;
width: 170px;
background-color: #fff;
box-shadow: 1px 0 #ccc,0 1px #ccc,-1px 0 #ccc,0 -1px #ccc;
visibility: hidden;
}
[type=search]:focus + label{
visibility: visible;
}
</style>
</head>
<body>
<input type="search" name="">
<label for="city">
<div class="list" data-ciry="广州guangzhou">广州市</div>
<div class="list" data-ciry="哈尔滨haerbin">哈尔滨市</div>
<div class="list" data-ciry="深圳shenzhen">深圳市</div>
<div class="list" data-ciry="长春changchun">长春市</div>
<div class="list" data-ciry="成都chengdu">成都市</div>
<div class="list" data-ciry="北京beijing">北京市</div>
<div class="list" data-ciry="上海shanghai">上海市</div>
<div class="list" data-ciry="台北taibei">台北市</div>
</label> <script type="text/javascript">
var s = document.createElement('style'),
input = document.querySelector('input'); document.head.appendChild(s); input.addEventListener('input',function(){
if(this.value !== ''){
s.innerHTML = '.list:not([data-ciry*=' + this.value + ']){display:none}';
}
else{
s.innerHTML = '';
}
}) </script>
</body>
</html>

首先思路就是利用Input的focus伪类来实现下拉的隐藏显示,其次就是一个input事件给不匹配的城市给隐藏掉。

具体可参考这里