<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.search{
width:700px;
margin:100px auto 0;
}
.search>p>span{
width:600px;
height:35px;
border:solid 3px #900;
display: inline-block;
}
input{
outline:none;
}
.search input[type="text"]{
width:500px;
height:29px;
border:none;
padding-left: 10px;
}
.search input[type="button"]{
width:94px;
height:29px;
background: #900;
color:#fff;
font-size: 14px;
text-align: center;
font-weight: bold;
line-height: 29px;
border:none;
cursor: pointer;
}
#show{
width:506px;
border:solid 1px #aaa;
border-top: none;
/*visibility: hidden;*/
}
#show p{
line-height: 30px;
text-indent: 5px;
font-weight: bold;
}
#show p:hover{
background: #900;
color:#fff;
}
</style>
</head>
<body>
<div class="search">
<p><span><input type="text" id="searchbox" placeholder="请输入搜索关键词"/><input type="button" value="搜索" id="searchbtn"/></span></p>
<div id="show">
</div>
</div>
<script>
var datalist=["hello","welcome","china","huawei","internationl","west","linux","fighting"];//定义数据库数组
var searchbox=document.getElementById("searchbox");//获取文本框
var show=document.getElementById("show");//获取显示对象
searchbox.onkeyup=function(){//文本框在键盘松开时触发
var zhi=this.value;// 提取当前文本框中的内容
var newdata=[];// 定义一个空数组
show.style.visibility="visible";// 默认让显示对象内容显示
show.innerHTML="";//默认情况下清空显示内容
for(var x=0;x<datalist.length;x++){ //遍历数据库数组内容
if(zhi.trim().length>0 && datalist[x].indexOf(zhi)>-1){ //判断当输入的值不为空且在数据库中能查找到时
newdata.push(datalist[x]);//把对应的数据添加到新数组中
}
}
// console.log(newdata.valueOf())
/*显示数据*/
for(var y=0;y<newdata.length;y++){ //遍历新数组
var newp=document.createElement("p");//创建新元素p
newp.innerHTML=newdata[y]; //把遍历对应的数组内容赋值给新元素 p中
show.appendChild(newp); //把新元素内容添加到显示元素中
}
//点击选中数据,并隐藏数据列表
var ps=document.getElementById("show").children; // 找到所有的显示元素中的子元素p
for(var i=0;i<ps.length;i++){ //遍历所有子元素
ps[i].onclick=function(){ //点击对应子元素时触发
searchbox.value=this.innerHTML;// 将点击的元素内容添加到搜索文本中
show.style.visibility="hidden";//把显示数据列表隐藏
}
}
}
</script>
</body>
</html>
JS下拉框搜索
最新推荐文章于 2024-08-31 18:03:39 发布