您的位置:首页 > Web前端 > JavaScript

百度一下 自动提示 js

2016-12-27 22:20 363 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
fieldset, img, input, button {
border: none;
padding: 0;
margin: 0;
outline-style: none;
}

ul, ol {
list-style: none;
margin: 0px;
padding: 0px;
}

#box {
width: 405px;
margin: 200px auto;
position: relative;
}

#txtSearch {
float: left;
width: 300px;
height: 32px;
padding-left: 4px;
border: 1px solid #b6b6b6;
border-right: 0;
}

#btnSearch {
float: left;
width: 100px;
height: 34px;
font: 400 14px/34px "microsoft yahei";
color: white;
background: #3385ff;
cursor: pointer;
}

#btnSearch:hover {
background: #317ef3;
}

#pop {
width: 303px;
border: 1px solid #ccc;
padding: 0px;
position: absolute;
top: 34px;
}

#pop ul li {
padding-left: 5px;
}

#pop ul li:hover {
background-color: #CCC;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="txtSearch">
<input type="button" value="百度一下" id="btnSearch">
</div>
<script>
var datas = ["a", "abc", "abbbb", "abxxxx", "xyz", "abcdef", "abzzzz"];
var text = document.getElementById("txtSearch");
var btnSearch = document.getElementById("btnSearch");
text.onkeyup = function () {
var val = this.value;
var filterArr = [];
for (var i = 0; i < datas.length; i++) {
if (datas[i].indexOf(val) == 0) {
filterArr.push(datas[i]);
}
}

//3.改bug
//3.1根据匹配数组创建结构之前先判断一下页面上是否已经存在pop了
var popDiv = document.getElementById("pop");
if (popDiv) {
//如果进来了 说明已经有了 就要把他干掉
box.removeChild(popDiv);
}
//3.2如果没有匹配项 就不要创建pop了
if (filterArr.length === 0) {
return;
}
//3.3如果是空字符串 就不创建了
//if(val.length===0)
if (val === "") {
return;
}

var popDiv = document.createElement("div");
popDiv.id = "pop";
box.appendChild(popDiv);
var ul = document.createElement("ul");
popDiv.appendChild(ul);
for (var i = 0; i < filterArr.length; i++) {
var li = document.createElement("li");
li.innerText = filterArr[i];
ul.appendChild(li);
li.onclick = function(){
text.value = this.innerText;
box.removeChild(popDiv);
};
}
}
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: