<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin:0; padding: 0; } #search{ 600px; margin:0 auto; margin-top: 100px; position: relative; } #search input{ 480px; height: 100%; border: 1px solid #b6b6b6; height: 20px; padding: 9px 7px; font: 16px arial; border: 1px solid #b8b8b8; border-bottom: 1px solid #ccc; border-right: 0; vertical-align: top; outline: none; box-shadow: none; -webkit-appearance: textfield; background-color: white; -webkit-rtl-ordering: logical; user-select: text; } #search button{ cursor: pointer; box-sizing: border-box; 97px; height: 40px; line-height: 38px; padding: 0; border: 0; background: none; background-color: #38f; font-size: 16px; color: white; box-shadow: none; font-weight: normal; margin-left: -20px; } .result{ position: absolute; padding: 9px 7px; background: #ddd; } .search-res{ position: absolute; top: 100%; left: 0; 480px; border: 1px solid #b6b6b6; border-top: none; } .search-res li{ list-style-type: none; line-height: 20px; padding: 2px 5px; border-bottom: 1px solid #b6b6b6; } .color{ background-color: red; } </style> <script src="../jsonp.js"></script> </head> <body> <div id="search"> <input type="text"> <button>搜索</button> <ul class="search-res"> </ul> </div> </body> <script> function Search() { this.txt=document.querySelector("#search input") this.ul=document.querySelector(".search-res"); this.ali=this.ul.children this.j=0; this.url="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su" //百度搜索接口 this.addEvent() } Search.prototype.addEvent=function () { var that=this; this.txt.onkeyup=function () { that.value=this.value; that.load() } }; Search.prototype.load=function () { var that=this; jsonp(this.url,function(res){ console.log(res); that.res = res.s; //返回的是个对象,s是需要的那个key that.display(); },{ wd:this.value, columnName:"cb", cb:"gkioy" }) }; Search.prototype.display = function(){ //增加列数 // console.log(this.res) var str = ""; for(var i=0;i<this.res.length;i++){ str += `<li>${this.res[i]}</li>` } this.ul.innerHTML = str; this.color() }; Search.prototype.color=function () { var that=this for(var i=0;i<this.ali.length;i++){ this.ali[i].onmouseover=function () { this.style.backgroundColor="red" }; this.ali[i].onmouseout=function () { this.style.backgroundColor="" }; this.ali[i].onclick=function () { that.txt.value=this.innerHTML; that.ul.style.display="none" }; this.txt.onclick=function () { that.ul.style.display="block" } document.onkeydown=function (eve) { console.log(that.ali.length-1) var e=eve||window.event console.log(that.j) if(e.keyCode==40&& that.txt.value){ if(that.j==that.ali.length-1){ that.j=0 } else { that.j++ } that.ali[that.j].className="color" }; if(e.keyCode==38 && that.txt.value){ if(that.j==0){ that.j=that.ali.length-1 } else { that.j-- } that.ali[that.j].className="color" }; } } }; new Search() </script> </html>