1. 效果
image.png
2. 原理
3. 实现代码
html
<div class="search">
<input type="text" class="ipt"/>
<input type="button" value="搜索" />
<ul class="relevant">
<li>123</li>
<li>456</li>
</ul>
</div>
css
*{
margin: 0;
padding: 0;
list-style: none;
outline: none;
border: none;
box-sizing: border-box;
}
.search{
width: 202px;
height: 35px;
border: 1px solid #666;
font-size: 0;
box-sizing: border-box;
margin: 50px auto;
position: relative;
}
.search input{
font-size: 18px;
height: 100%;
line-height: 35px;
width: 150px;
/*防止遮挡input*/
vertical-align: top;
padding: 0 4px;
}
.search input[type=button]{
width: 50px;
text-align: center;
cursor: pointer;
}
.relevant{
position: absolute;
top: 33px;
left: -1px;
width: 152px;
border: 1px solid #666;
/*一开始刷新的时候隐藏掉*/
display: none;
}
.relevant li{
width: 100%;
height: 30px;
line-height: 30px;
padding: 0 5px;
border-bottom: 1px dashed #999;
font-size: 16px;
cursor: pointer;
/*一行文字,超出部分省略号表示*/
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.relevant li:hover{
background: gainsboro;
}
.relevant li:last-child{
border-bottom: none;
}
js
let ipt =document.querySelector(".ipt");
var _ul = document.querySelector(".relevant");
//封装函数-动态获取数据-jsonp
function getData(_url,keyW){
//清除之前添加的script标签
var spt = document.querySelector("script[src]");//找到文档中所有的script[src]
if(spt!=null){//判断刚开始为null不用清除
spt.remove();
}
//重新添加新的script标签-jsonp
var _script = document.createElement("script");
_script.src = _url;
document.body.appendChild(_script);
}
//监听用户输入框
ipt.addEventListener("input",()=>{
let val = ipt.value;
let _url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+val+"&cb=callback";
getData(_url);//调用函数
})
//给_url的callback声明一个全局函数,这里的callback是引入地址里面的回调函数
function callback(res){
_ul.style.display = "block";
_ul.innerHTML = "";//清空上一次的搜索
for(var i=0;i<res.s.length;i++){
var _li = "<li>"+res.s[i]+"</li>";
_ul.innerHTML += _li;
}
if(res.s.length==0){
_ul.style.display="none";
}
}
//点击相关内容,替换文本框内容 --- 事件代理:
_ul.addEventListener("click",(e)=>{
let txt = e.target.innerText;
ipt.value = txt;
_ul.style.display = "none";
})
//点击搜索跳转到百度相关内容搜索
let btn = document.querySelector("input[type=button]");
btn.addEventListener("click",()=>{
window.open("https://www.baidu.com/s?ie=utf8&wd="+ipt.value+"&tn=87048150_dg")
网友评论