在一个网站中,搜索框是必不可少的,而根据网站类型不同,搜索操作无非就两种,一是用户输入动作完成点击搜索按钮进行搜索,二是用户输入动作完成js进行自动搜索,第一种比较简单,通过绑定方法方法就能实现,第二种方法实现起来稍微复杂一点,需要监听用户动作,实现如下:
搜索前效果
搜索后效果
第二种方法
<link rel='stylesheet' href='//at.alicdn.com/t/font_1940919_21d7ie8hypo.css'><script src='https://cdn.bootcss.com/jquery/1.11.1-rc2/jquery.min.js'></script>
<style>
body{
background: #ededed;
}
.search-wrapper{
height: 40px;
margin: 10px;
display: flex;
font-size: 14px;
position: relative;
}
.search-wrapper input{
flex: 1;
height: 100%;
border: none;
background: #fff;
border-radius: 5px;
line-height: 40px;
padding:0 30px;
}
.search-cancel{
flex: 0 0 40px;
width: 40px;
text-align: right;
line-height: 40px;
color: #667aa3;
}
.input-search,.input-cancel{
position: absolute;
left: 0px;
top: 0px;
width: 30px;
height: 40px;
text-align: center;
line-height: 40px;
}
.input-cancel{
left: calc(100% - 70px);
color: #67676a;
display: none;
}
.search-list-wrapper{
margin: 10px 0;
padding: 0 0 0 10px;
background: #fff;
display: none;
}
.search-list-wrapper li{
width: 100%;
height: 40px;
display: flex;
padding: 10px 0;
}
.search-list-wrapper li img{
height: 100%;
flex: 0 0 40px;
width: 40px;
object-fit: cover;
border-radius: 2px;
}
.search-list-wrapper li p{
line-height: 40px;
margin-left: 15px;
flex: 1;
border-bottom: 0.5px solid rgba(237,237,237,0.8);
box-sizing: border-box;
font-size: 14px;
margin-bottom: -10px;
}
.search-list-wrapper li:last-child p{
border: none;
}
.search-list-title{
border-bottom: 0.5px solid rgba(237,237,237,0.8);
font-size: 12px;
line-height: 40px;
height: 30px;
}
.search-empty{
font-size: 12px;
text-align: center;
line-height: 30px;
color: #67676a;
display: none;
}
</style>
<div class='search-wrapper'>
<i class='iconfont buy-search input-search'></i>
<input type='text' placeholder='搜索' class='search-hook'>
<i class='iconfont buy-cancel input-cancel' onclick='cancelInput()'></i>
<div class='search-cancel' onclick='window.history.go(-1)'>取消</div>
</div>
<p class='search-empty'>未搜索到指定选手</p>
<div class='search-list-wrapper'>
<p class='search-list-title'>搜索列表</p>
<ul class='search-list-content'></ul>
</div>
//监听输入拼音,当用户在输入拼音时不进行操作
var compositionFlag = true;
$(".search-hook").on('compositionstart',event => {
// 中文输入法开始输入
compositionFlag = false;
}).on('compositionend',event => {
// 中文输入法结束输入
compositionFlag = true;
});
//监听input值发生变化
var inputVal = $(".search-hook").val();
var tmp = "";
var flag = 1;
//定时500毫秒,监听input元素值是否发生变化,当input500毫秒未发生变化,且存在搜索内容,且该搜索内容未被搜索时,调用方法进行搜索
setInterval(function () {
let val = $(".search-hook").val();
if(val && val == tmp && val != inputVal && compositionFlag)
{
console.log("在此执行ajax请求");
tmp = val;
inputVal = val;
}else if(val) {
tmp = val;
}
//判断是否显示清空图标
if(val)
{
$(".input-cancel").show();
}else {
$(".input-cancel").hide();
}
},500);