3.js代码
var block=document.getElementsByClassName("block")[0];//获取block var ser=document.getElementById ("txt");//获取搜索框 var bd=document.getElementById("baidu");//获取baidu bd.οnclick=function(){//给百度一个点击事件函数 location.href="https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd="+ser.value; } ser.οnkeyup=function(){//1.首先写鼠标抬起事件 var sce=document.getElementsByClassName ("sce"); if(sce.length){ sce[0].remove(); sce[0].remove(); } var d_src=document.createElement("script");// 2.在鼠标事件中动态创建script标签 d_src.className="sce";//给script标签添加class名称 //给标签一个百度路径:cb(回调函数) wd:(键值) this.value当前输入的文本 d_src.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=showdata&wd="+this.value; document.head.appendChild(d_src);//将script标签追加给头部 //由于需要写回调函数,所以需要再创建一个script标签 var m_src=document.createElement("script"); m_src.className="sce"; document.head.appendChild(m_src); m_src.innerHTML=showdata; function showdata(data){//回调函数 //获取ul var ullist=document.getElementsByClassName("ullist"); if(ullist.length){ ullist[0].remove(); }//移除上次搜索出现的ul var ul=document.createElement("ul"); //创建ul ul.className="ullist"; for(var i=0;i<data.s.length;i++){//动态获取对象s中的元素,并将其显示在li中 var li=document.createElement("li"); li.innerHTML="<a href='https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd="+data.s[i]+"'>"+data.s[i]+"</a>"; ul.appendChild(li);//将li追加给ul } block.appendChild(ul);//将ul追加给block } }
css代码
*{
margin: 0;
padding: 0;
}
.block{
position: relative;
width: 500px;
height: 45px;
border: 1px solid black;
margin: 13% auto;
}
.block input{
width: 390px;
height: 40px;
padding-left: 10px;
border-style:none;
outline: none;
font-size: 18px;
float: left;
}
#baidu{
display: inline-block;
width: 100px;
height: 45px;
float: left;
color: white;
line-height: 45px;
font-size: 18px;
background-color: #7d84e3;
text-align: center;
cursor: pointer;
}
.ullist{
position: absolute;
left: -1px;
top: 45px;
background-color: white;
border: 1px solid silver;
height: auto;
width: 360px;
}
.ullist li{
list-style: none;
font-size: 14px;
line-height: 30px;
cursor: pointer;
}
.ullist li:hover{
background-color: #e0e0e0;
cursor: pointer;
}
.ullist li a{
text-decoration: none;
color: black;
}
.html代码
<div class="block">
<input id="txt" type="text">
<span id="baidu">百度一下</span>
</div>