<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#box {
width: 450px;
margin: 200px auto;
}
#txt {
width: 350px;
}
#pop {
width: 350px;
border: 1px solid red;
}
#pop ul {
margin: 10px;
padding: 0px;
width: 200px;
list-style-type: none;
}
#pop ul li {
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="txt" value="">
<input type="button" value="搜索" id="btn">
</div>
<script>
var keyWords = ["小杨才是最纯洁的", "小杨才是最帅的", "小段是最猥琐的", "小超是最龌龊的", "传智播客是一个培训机构", "传说在传智有个很帅很纯洁的小杨", "苹果好吃", "苹果此次召回还是没有中国"];
//获取键盘抬起事件
document.getElementById("txt").onkeyup = function(){
if(document.getElementById("dv")){
//删除一次
document.getElementById("box").removeChild(document.getElementById("dv"));
}
//获取文本框中输入的内容
var text = this.value;
var tempArr = [];
//把文本框中的内容与数组中的每个数据对比
for(var i=0;i<keyWords.length;i++){
//判断是否是最开始出现的
if(keyWords[i].indexOf(text)==0){
tempArr.push(keyWords[i]);
}
}
//文本框或者临时数组为空,则表示不需要创建div
if(text.length==0|| tempArr.length==0){
if(document.getElementById("dv")){
document.getElementById("box").removeChild(document.getElementById("dv"));
}
return;
}
//创建一个div
var divObj = document.createElement("div");
document.getElementById("box").appendChild(divObj);
divObj.id="dv";
//设置div的宽和高
divObj.style.width="350px";
//divObj.style.height="100px";
divObj.style.border="1px solid green";
//循环遍历临时数组,创建对应的p标签
for(var i=0;i<tempArr.length;i++){
//创建一个p标签
var pObj = document.createElement("p");
//将p加到div中
divObj.appendChild(pObj);
setInnerText(pObj,tempArr[i]);
pObj.style.margin=0;
pObj.style.padding = 0;
pObj.style.cursor="pointer";
pObj.style.marginTop = "5px";
pObj.style.marginLeft = "5px";
//鼠标进入
pObj.onmouseover = function () {
this.style.backgroundColor = "yellow";
};
//鼠标离开
pObj.onmouseout = function () {
this.style.backgroundColor = "";
};
}
};
//设置标签内容
function setInnerText(element, text) {
if (typeof element.textContent == "string") {
element.textContent = text;
} else {
element.innerText = text;
}
}
</script>
</body>
</html>