<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } body{ background: #cfcfcf; } #projectSearch{ position: relative; width: 400px; margin: auto; margin-top:100px ; } #inputSearch{ position: absolute; left: 0; top: 0px; width: 400px; height: 40px; text-indent: 10px; border-radius: 5px; border: 1px solid yellowgreen; } #projectList{ position: absolute; left: 0; top: 43px; width: 400px; height: 180px; overflow: hidden; cursor: pointer; border: 1px solid yellowgreen; } .item{ display: block; height: 30px; line-height: 30px; text-decoration: none; color: #000; text-indent: 10px; } .item:hover{ background: #00A8E6; } </style> </head> <body> <div id="projectSearch"> <input type="text" id="inputSearch" placeholder="请输入要搜索的文字"> <div id="projectList"></div> </div> </body> <script> var inp=document.getElementById('inputSearch'); var projectList=document.getElementById('projectList'); inp.onkeyup=function () { //获取input框的值 var text=inp.value; let timer=null; timer && clearTimeout(timer); timer=setTimeout(function () { var lastkey=text; var url="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+lastkey+"&cb=callback" // 动态生成script的标签 var script=document.createElement('script'); //设置script的src属性 script.setAttribute('src',url); //最后插入到页面中 document.getElementsByTagName('head')[0].appendChild(script) },200); }; // 成功后的回调函数 function callback(data) { console.log(data.s); var item=''; for(var i=0;i<data.s.length;i++){ item+="<a href='#' class='item'>"+data.s[i]+"</a>" } console.log(item); projectList.innerHTML=item } </script> </html>
效果为
用到了利用jsonp来实现跨域,动态生成script的标签,利用script的src的属性来实现跨域