使用JavaScript实现搜索框 搜索本页内容的功能
来源:网络收集 点击: 时间:2024-08-28先打开Sublime选择HTML编辑模式,将文件保存为js_search,然后正式开始编写,如下:

body内容使用div标签创建一个块,放置输入框以及一个列表,列表中随便显示些内容,如下:
div class=box
input type=text id=searchInp
ul id=searchList
lia href=javascript:;早上好/a/li
lia href=javascript:;中午好/a/li
lia href=javascript:;晚上好/a/li
lia href=javascript:;半夜好/a/li
lia href=javascript:;凌晨好/a/li
/ul
/div

搜索框的style设置如下:
style
*{
margin:0;
padding:0;
font-size:14px;
}
input{
display:block;
outline:none;
}
a{
display:block;
text-decoration: none;
color:#000;
}
a:hover,a:active,a:target{
text-decoration: none;
color:#000;
}
ul,li{
list-style:none;
}
.box{
position:absolute;
top:20px;
left:50%;
margin-left:-250px;
width:500px;
}
.box input{
width:300px;
height:35px;
padding:0 10px;
border:1px solid #008000;
}
.box ul{
display:none;
position:relative;
top:-1px;
border:1px solid #008000;
}
.box ul li,.box ul li a{
height:35px;
line-height:35px;
}
.box ul li a{
padding:0 10px;
}
.box ul li a:hover{
background:#ccc;
}
/style


script下document实现如下:
var searchInp = document.getElementById(searchInp),searchList = document.getElementById(searchList);
searchInp.onkeyup = searchInp.onfocus = function(){
var val = this.value.replace(/(^ +| +$)/g,)
searchList.style.display = val.length 0 ? block : none;
}
document.body.onclick = function(e){
e = e || window.event;
e.target = e.target || e.srcElement;
if(e.target.tagName.toLowerCase()===a e.target.parentNode.parentNode.id===searchList){
searchList.style.display = none;
searchInp.value = e.target.innerHTML;
return;
}
searchList.style.display = none;
}

搜索输入框响应方法如下:
searchInp.onclick = function(e){
e = e || window.event;
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}

双击保存的文件在网页中打开,可以看到默认显示出搜索框,当我们输入东西时会自动搜索页面的内容,如下:



版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.ff371.cn/art_1161574.html