话不多说,直接上代码!相信老铁们,都能看明白!注释就不加啦!
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.bg{ background:gray;
} </style></head><body><input type="text" id="search"><div></div></body><script>
var search=document.querySelector("#search"); var div=document.querySelector("div"); var p=document.getElementsByTagName("p"); var index=-1; var keyWord=""; function fn(obj){
div.innerHTML=null;
keyWord=obj.q; for(var i=0;i<obj.s.length;i++){ var p=document.createElement("p");
p.innerHTML=obj.s[i];
div.appendChild(p);
}
} document.onkeydown=function(e){ var ev=e ||window.event; if(ev.keyCode==40){ for(var i=0;i<p.length;i++){
p[i].className=null;
}
index++; if(index>(p.length-1)){
index=-1;
search.value=keyWord;
}else{
p[index].className="bg";
search.value=p[index].innerHTML;
}
}else if(ev.keyCode==38){ for(var i=0;i<p.length;i++){
p[i].className=null;
}
index--; if(index<-1){
index=p.length-1;
} if(index<0){
search.value=keyWord;
}else{
search.value=p[index].innerHTML;
p[index].className="bg";
}
}else if(ev.keyCode==13){ window.open("https://www.baidu.com/s?wd="+search.value);
}
}
search.oninput=function(){ var script=document.createElement("script");
script.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+this.value+"&cb=fn"; document.body.appendChild(script); document.body.removeChild(script);
}</script></html>
作者:张培跃
链接:https://www.jianshu.com/p/fe56c695f0dd