先来效果图
图片一:
图片二:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
center{
line-height: 40px;
font-size: 20px;
}
.father{
width:500px ;
}
.searchFath{
padding-top: 200px;
}
.searchIn{
width: 400px;
height: 40px;
font-size: 20px;
}
.searchBtn{
height: 40px;
width: 50px;
text-align: center;
}
ul{
list-style: none;
}
li{
}
</style>
</head>
<body>
<center>
<div class="father">
<div class="searchFath">
<input class="searchIn">
<button class="searchBtn">查询</button>
</div>
<div class="content"></div>
</div>
</center>
<script>
//搜索框
var searchIn;
//button按钮
var searchBtn;
//上一次搜索的文字
init();
function init() {
searchIn=document.querySelector('.searchIn');
//给input添加节流搜索
searchIn.addEventListener('input',()=>{
setTimeout(()=>{
creatJsonp(searchIn.value);
},1000)
});
searchBtn=document.querySelector('.searchBtn');
searchBtn.addEventListener('click',()=>search(searchIn.value));
document.addEventListener('keydown',(e)=>{
if (e.key === 'Enter') {
search(searchIn.value);
}
});
}
//创建jsonp请求
function creatJsonp(word) {
var script=document.createElement("script");
script.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+word+"&json=1&p=3&sid=22084_1436_13548_21120_22036_22073&req=2&csor=0&cb=callback";
document.body.appendChild(script);
script.addEventListener('load',()=>script.remove());
}
//jsonp的回调函数
function callback(obj) {
var child=document.querySelector('.content').firstElementChild;
if(child){
child.remove();
}
creatContent(obj.s);
}
//创建li标签,即搜索提示栏
function creatContent(arr) {
let ul=document.createElement('ul');
arr.forEach(
(value)=>ul.appendChild(
crElE('li',value,()=>search(value))
)
);
document.querySelector('.content').appendChild(ul);
}
//创建元素,并给其添加文本内容及监听点击回调
function crElE(nodeName,textContent,clickCallback) {
let ele=document.createElement(nodeName);
ele.textContent=textContent;
ele.addEventListener('click',clickCallback);
return ele;
}
//百度搜索
function search(text) {
window.location.href='https://www.baidu.com/s?tn=02049043_8_pg&ch=3&isource=infinity&wd='+text;
}
</script>
</body>
</html>