简陋的百度搜索框.练习记录。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="box">
<input type="text" id="txt" value=""/>
<input type="button" id="btn" value="搜索">
</div>
<script>
var keyWords = ["123", "1234", "113", "156", "189", "998", "121", "1369"];
var txt=document.getElementById("txt");
var btn=document.getElementById("btn");
txt.onkeyup=function () {
//刷新框
if (document.getElementById("dv"))
document.getElementById("box").removeChild(document.getElementById("dv"));
//根据输入,将keyword中类似的词放到arr中
var text=this.value;
var arr=[];
for (var i=0;i<keyWords.length;i++){
if (keyWords[i].indexOf(text)==0){
arr.push(keyWords[i]);
}
}
//根据输入决定要不要创建框
if (this.value.length==0||arr.length==0){
if (document.getElementById("box"))
document.getElementById("box").removeChild(document.getElementById("dv"));
return;
}
//创建框
var dv=document.createElement("div");
document.getElementById("box").appendChild(dv);
dv.id="dv";
dv.style.width="350px";
dv.style.border="1px solid #ccc";
//创建p
for (var i=0;i<arr.length;i++){
var op=document.createElement("p");
dv.appendChild(op);
op.innerHTML=arr[i];
op.onmouseover=function () {
this.style.backgroundColor="green";
}
op.onmouseout=function () {
this.style.backgroundColor="";
}
}
}
</script>
</body>
</html>