搜索框内容自动提示
案例效果
案例步骤
1.获取搜索框并为其添加用户输入事件
2.获取用户输入的关键字
3.向服务器端发送请求并携带关键字并作为请求参数
4.将响应数据显示在搜索框底部
5. 开启服务器,在浏览器地址栏中,输入****localhost:3000/01.搜索框内容自动提示.html
****
6. 实现效果
HTML代码
<div class="container">
<input type="search" id="search" placeholder="请输入搜索关键字">
<ul class="list-group">
</ul>
</div>
CSS代码
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
li{
list-style: none;
}
.container{
width: 1000px;
height: 40px;
background-color: red;
margin: 100px auto;
}
.container #search{
width: 1000px;
outline: none;
text-indent: 2px;
height: 100%;
}
.list-group{
border: 1px solid;
width: 100%;
display: none;
margin-top: -1px;
}
.list-group li{
padding: 10px;
cursor: pointer;
}
.list-group li:hover{
color: lightblue;
}
</style>
JS代码
在此处需要使用template模板,将其引入到页面中。由于当用户在文本框中输入的时候触发oninput事件,所以就会不断发送请求,此时就需要使用定时器延迟请求的发送。
<script src="./js/ajax.js"></script>
<script src="./js/template-web.js"></script>
<script id="tpl" type="text/html">
{
{
each result}}
<li class="list-group-item">