效果如上图 点击时跳转。
以下附上整个界面的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
padding:0;
margin:0;
list-style:none;
text-decoration: none;
}
div{
margin:100px;
}
input{
width:400px;
height:40px;
}
ul{
border:2px solid #eee;
width:400px;
}
li:hover{
background: #ddd;
}
a{
font-size:14px;
display: inline-block;
width:100%;
color:#999;
padding:5px;
}
</style>
</head>
<body>
<div>
<input type="text">
<ul></ul>
</div>
<script>
//获取dom元素
var oInput = document.getElementsByTagName('input')[0];
var oUl = document.getElementsByTagName('ul')[0];
document.addEventListener('click',function(){
oUl.style.display = 'none';
});
//给input添加事件
oInput.oninput = function(){
var value = this.value;
myJsonp(value,'search');
oUl.style.display = 'block';
};
//给li添加事件,不如直接给父元素UL添加事件,可以利用事件源对象获取当前点击的li(可扩展性强)
oUl.addEventListener('click',function(e){
oInput.value = e.target.innerHTML;
oUl.style.display = 'none';
},false);
function myJsonp(value,callback){
var oScript = document.createElement('script');
oScript.src = 'https://www.baidu.com/sugrec?prod=pc&wd='+value+'&cb='+callback;
document.body.appendChild(oScript);
document.body.removeChild(oScript);
}
//回调函数,渲染搜索列表,需要注意,设置样式时给a标签设置width100%充满,不能点到li身上,而且也不能给
// li设置padding,给a设置margin,都不可以,只能给a设置padding,不然就无法跳转了。
function search(data){
if(data.g){
var str = '';
data.g.forEach(function(item,index){
str+='<li><a href ="https://www.baidu.com/s?wd='+item.q+'">'+item.q+'</a></li>';
});
oUl.innerHTML = str
}
}
</script>
</body>
</html>