今天的效果如下:

这个案例的要点有两个:

==一==是使用CSS显示样式

==二==是使用js比较输入的内容和数组中的内容使得包含输入内容的数据显示出来

首先来看==CSS显示样式==的难点:

两个div的接触部分,要想让它们无缝隙接触,就需要设置float:left

两个div盒子左右两侧的圆角边框,我们需要分别为border-top-left-radius等设置值,这样就大致得到了搜索框的样式,剩下的细节可以去代码中查看~

接着来看==JS进行比较==的部分:

总的思想呢,就是当输入内容时使下方显示搜索框,显示匹配的数据;不输入或输入数据不匹配时,不显示数据或显示暂无数据;搜索框失去焦点时使下方的搜索框消失

  1. 当我们在搜索框中输入内容时,我们可以调用onkeyup函数,先使下方的搜索框display属性值为block;
    然后在其中调用forEach遍历数组中的所有数据,通过value获得输入的内容,调用indexOf将该内容与数组中的数据进行比较,若有匹配项的话,其返回值是数组中数据的下标,否则为-1;
    若有匹配项的话,我们可以利用innerHTML,在下面的显示框中添加p标签,p中的内容是匹配的数据;如果没有就返回内容是‘暂无数据’的p标签
  2. 当该搜索框失去焦点时,我们令下方搜索框的display属性值为none就可以了

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.container {
width: 500px;
height: 160px;
padding: 40px;
margin: 100px auto
}

#one {
width: 268px;
height: 33px;
float: left;
border: 0;
border-top-left-radius: 20px;
border-bottom-left-radius: 20px;
background-color: rgb(245, 246, 247);
outline: none;
}

#search {
background-color: rgb(252, 85, 49);
color: white;
width: 70px;
height: 35px;
line-height: 35px;
text-align: center;
font-size: 13px;
border-radius: 20px;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
float: left;
}

#show {
width: 270px;
height: 170px;
border: 1px solid rgba(77, 76, 76, 0.459);
display: none;
margin-top: 40px;
overflow: hidden;
}
#show div{
width: 100%;
height: 40px;
line-height: 40px;
text-indent: 1em;
display: block;
}
#show div:hover{
background-color: rgb(240, 240, 245);
cursor:pointer;
}
</style>
</head>

<body>
<div class="container">
<div id="nav">
<input type="text" id="one" placeholder="请输入课程" autocomplete="on">
<div id="search">搜索</div>
</div>
<div id="show">
<div></div>
</div>
</div>

<script>
let arr = ['蛋糕便宜卖', '想吃水果', '2333', 'css精品课程','2个小朋友','这儿有2个面包','我们一起','乐队的夏天','天气真好'];
let one = document.getElementById("one");
let show = document.getElementById("show")

one.onfocus = function () {
show.style.display = "block";
one.style.border = "1px coral solid"
one.onkeyup = function () {
let str = '';
let tem=false;
arr.forEach((item) => {
let index = item.indexOf(one.value);
if (~index) {
tem=true;
str+='<div>'+item+'</div>';//每次都更新str的值,所以不用担心重复
}
})
//很重要
if(one.value=='' || !tem){
show.innerHTML='<div>'+'暂无结果'+'</div>';
}
else{
show.innerHTML=str;
}
}

}
//onblur 的事件会在对象失去焦点时发生
one.onblur = function () {
show.style.display = "none"
one.style.border = "1px transparent solid"
show.innerHTML='';
}
</script>
</body>

</html>