使用JS location实现搜索框历史记录功能
首先,来看下效果图(样式什么的就不必吐槽了哈)
html代码
搜索记录:
//用于保存记录信息
css代码
*{
margin:0;
padding:0;
}
input{
border:0;
vertical-align:middle;
float:left;
}
#searchbox{
width:300px;
height:50px;
background:#fff;
margin:100pxauto;
border:1pxsolid#ccc;
position:relative;
}
#inpt{
width:240px;
height:50px;
outline:none;
text-indent:10px;
}
#btn{
width:60px;
height:50px;
cursor:pointer;
}
/*历史记录框*/
#historybox{
width:280px;
padding:10px10px50px;
border:1pxsolid#ccc;
position:absolute;
top:50px;
left:-1px;
/*隐藏*/
display:none;
}
#historyboxh3{
margin-bottom:10px;
}
#list{
list-style:none;
}
#list.on{
float:left;
border:1pxsolid#ccc;
background:#aaa;
height:30px;
line-height:30px;
margin:02px;
border:1pxsolid#ccc;
border-radius:5px;
}
#list.active{
color:#fff;
text-decoration:none;
padding:2px;
}
js代码(这里需引入jQuery)
$(function(){
letmax_history=7;//存储最大历史数据
//鼠标移入事件
$('#inpt').on('focus',function(){
$('inpt').val='';
letdata=localStorage.getItem('data');//从本地存储中读取数据
if(!data){
$('#historybox').css('display','none');
}else{
$('#historybox').css('display','block');
historydata(JSON.parse(data));//渲染数据
}
})
//鼠标移出事件
$('#inpt').on('blur',function(){
$('#historybox').css('display','none');
init_history();//初始化历史记录,清空记录
})
//点击搜索按钮时,将搜索内容添加到本地存储
$('#btn').on('click',function(){
varsearch=inpt.value;
vardata=localStorage.getItem('data');//从本地存储中读取数据
if(data){
vararr=JSON.parse(data);//如果有数据则转换成对象或数组
}else{
vararr=[];//如果没有数据,则新增一条
}
arr.push(search);
removalDuplicate(arr);//对用户输入值进行处理(去重-筛选)
localStorage.setItem('data',JSON.stringify(arr));//将数据写入到本地存储中
})
//数组去重-筛选函数
functionremovalDuplicate(arr){
for(leti=0;i${searchArr[i]}`);
}
}else{//否则渲染最大历史记录条数
for(leti=0;i${searchArr[i]}`);
}
}
}
//初始化-清空历史记录
functioninit_history(){
$('#list').html('');
}
})
总结
以上所述是小编给大家介绍的使用JSlocation实现搜索框历史记录功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。