用onekeyup
事件
html结构:
<div class="flex-box">
<span><input type="text" placeholder="请输入关键字" id="text"></span>
<span><input type="button" value="搜索"></span>
</div>
<div id="box"></div>
CSS:
* {
margin: 0;
padding: 0;
}
input:focus {
outline: none;
}
.flex-box {
display: flex;
justify-content: center;
align-items: center;
margin-top: 300px;
}
.flex-box span {
display: inline-flex;
}
.flex-box span:nth-child(1) input {
width: 200px;
height: 30px;
border: 1px solid orange;
}
.flex-box span:nth-child(2) input {
width: 50px;
height: 32px;
border: 0;
background: orange;
color: #fff;
transition: ease-in .3s;
}
.flex-box span:nth-child(2) input:hover {
background: #ff9511;
}
#box {
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
#box div {
width: 200px;
border: #ff9511 1px solid;
border-top-color: white;
position: relative;
left: -1.3%;
}
#box p {
padding: 0;
margin: 0;
cursor:pointer;
}
#box p:hover {
background: orange;
}
这里提前把最后要生成元素的样式给写好。就不用在js里写了,当然你也可以创建元素的时候,直接写在js里 JS结构:
let text = document.getElementById("text");
let box = document.getElementById("box");
//这里建立数组只是模拟数据库
let arrays = ["Linux", "Linux哪个版本好用", "Linux安装QQ", "Linux好用吗", "百度和谷歌", "百度公司在哪里", "阿里巴巴", "马爸爸退休了吗?", "马爸爸什么时候退休的?", "还有", "还有多久过年"];
//直接调用处理函数
text.onkeyup = keyFun;
//创建处理函数
function keyFun() {
//判断dom里有没有id为active的元素,有就将他删除
if (document.getElementById("active")) {
box.removeChild(document.getElementById("active"));
}
//这里用到indexOf方法和push方法
let txt = this.value;
let temp = [];
for (let i = 0; i < arrays.length; i++) {
if (arrays[i].indexOf(txt) === 0) {
temp.push(arrays[i]);
}
}// end for
//判断当前文本框长度和临时数组长度是否为0,为true,执行代码块
if (this.value.length === 0 || temp.length === 0) {
if (document.getElementById("active")) {
box.removeChild(document.getElementById("active"));
}
return;//这里必须要返回return,不然这个生成的元素无法删除掉
}//end if
//这一步生成元素,并把临时数组遍历的值给p
let divObj = document.createElement("div");
box.appendChild(divObj);
divObj.id = "active";
for (let j = 0; j < temp.length; j++) {
let pObj = document.createElement("p");
divObj.appendChild(pObj);
pObj.innerHTML = temp[j];
}
}