纯js实现搜索框自动补全
- 开发语言:HTML+CSS+JS
- 编辑器:VSCode
- 构建思路:建立两个div,一个用于输入和搜索,一个用于展示,用于展示的初始状态为隐藏的。后面当有键盘输入事件时就显示,遍历数组,如果找到了我们要输入的就将其加入到展示的div里面,如果搜索框失去焦点就清空。
- 界面展示:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9c61e5f5eabef781b80584b44d4542ea.gif)
- 项目完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
*{
padding: 0;
margin: 0;
}
.box{
height: 400px;
width: 400px;
margin: 20px auto;
}
.search{
width: auto;
height: 45px;
margin-bottom: 0px;
}
.show{
display: none;
margin-top: 0px;
height: 300px;
width: 250px;
border: #eee solid 1px;
overflow: scroll;
}
#val{
padding-left: 20px;
height: 40px;
width: 230px;
}
#sub{
height: 40px;
width: 80px;
}
.show p{
margin-top: 0px;
margin-bottom: 0px;
color: grey;
padding-left: 15px;
}
</style>
<body>
<div class="box">
<div class="search">
<input type="text" id="val" placeholder="请输入关键字">
<input type="submit" id="sub">
</div>
<div class="show" id = "show">
<P>sb</P>
<p>sb</p>
</div>
</div>
</body>
</html>
<script>
var array = ["熊卓颖","罗铭","罗屌","段景伟","段晶伟","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿",
"胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿","胡邓懿"];
var val = document.getElementById('val');
var sub = document.getAnimations('sub');
var show = document.getElementById('show');
val.onkeyup = function(){
show.style.display = 'block';
var str = '';
for(let i = 0; i < array.length; i++)
{
if(array[i].indexOf(val.value) != -1)
str += "<p>"+array[i]+"</p>";
}
if(!val.value || !str)
show.innerHTML = "<p>没有这样东西</p>";
else
show.innerHTML = str;
var arrayList = show.getElementsByTagName("p");
for(let i = 0; i < arrayList.length; i++)
{
arrayList[i].addEventListener('click',function(){
alert(arrayList[i].innerText)
});
}
}
val.onblur = function(){
var t = 5;
setInterval(()=>{
t--;
if(t==0)
{
show.style.display = 'none';
val.value = "";
}
},(1000))
}
</script>