使用JavaScript实现搜索框 搜索本页内容的功能
1、先打开Sublime选择HTML编辑模式,将文件保存为js_search,然后正式开始编写,如下:

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

3、搜索框的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>


4、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";
}

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

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


