<!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 id="pop">-->
<!--<ul>-->
<!--<li></li>-->
<!--<li></li>-->
<!--<li></li>-->
<!--<li></li>-->
<!--</ul>-->
<!--</div>-->
</div>
<script>
var datas = ["a", "abc", "abbbb", "abxxxx", "xyz", "abcdef", "abzzzz","axxx","aaabbb","fjj"];
var txtSearch = document.getElementById("txtSearch");
var box = document.getElementById("box");
//根据输入的内容,显示datas里面包含了输入内容的那些字符串。
txtSearch.onkeyup = function () {
var arr = [];
// 遍历datas,挨个去判断,如果字符串包含了输入的内容,放到一个新数组里面
for(var i = 0; i < datas.length; i++) {
if(datas[i].indexOf(this.value) != -1){
//说明包含
arr.push(datas[i]);
}
}
console.log(arr);
//先判断一下,判断有没有id叫做pop的div,如果有,删除它
var pop = document.getElementById("pop");
if(pop){
box.removeChild(pop);
}
if(arr.length == 0 || this.value == ""){
return;
}
//根据arr来生成div, 生成div,添加到box,设置id
var div = document.createElement("div");
div.id = "pop";
box.appendChild(div);
//生成ul,添加到div
var ul = document.createElement("ul");
div.appendChild(ul);
// 生成li,添加到ul
for(var i = 0; i < arr.length; i++) {
var li = document.createElement("li");
li.innerHTML = arr[i];
ul.appendChild(li);
}
}
</script>
</body>
</html>
原文:https://www.cnblogs.com/miss-yang/p/10308757.html