使用原生js和jQuery实现百度搜索

使用的百度搜索接口

1、设置样式

使用原生js和jQuery实现百度搜索

2、为input绑定keyup事件,从百度搜索接口获得热关键词

使用原生js和jQuery实现百度搜索

3、点击关键字列表,可以跳转到相应的百度搜索界面

使用原生js和jQuery实现百度搜索

实现思路:

1、样式就不说了,直接上代码

	<div id="main">
		<div id="logo"></div>
		<form id="search-form">
			<input type="text" name="" id="search-input"/>
			<i id="search-icon"></i>
		</form>
	</div>
	<div id="search-results">
			<ul id="search-list">
			</ul>
	</div>
*{
	margin: 0;
	padding: 0;
}
body{
	background-color: #333;
	background-image: url(../images/river.jpg);
}
#main{
	margin-top:150px;
	margin-left:400px; 
}
#logo{
	width: 120px;
	height: 40px;
	background-image: url(../images/logo.png);
	float: left;
	margin-right: 20px;
	margin-top:-5px; 

}
#search-form{
	padding:5px;
	float: left;
	background-color: #fff;
}
#search-form #search-input{
	height: 25px;
	line-height: 25px;
	width: 388px;
	float: left;
	outline: none;
	border:none;
}
#search-form #search-icon{
	float: left;
	width: 29px;
	height: 29px;
	background-image: url(../images/search-button.png);
	outline: none;
	border:none;
}
#search-results{
	background-color: #fff;
	width: 428px;
	position: absolute;
	display:none;
}
#search-results ul{
	list-style: none;
	border:2px solid #c2c2c2;
}
#search-results ul li{
	padding: 2px;
	height: 25px;
	line-height: 25px;
	font-size: 14px;
}
#search-results ul li:hover{
	background-color: rgb(240,240,240);
	text-decoration: underline;
	cursor: pointer;
}

 

2、在input键入的时候绑定keyup事件,每次输入都向服务器发送ajax请求,并且使用jsop实现跨域,展示关键字列表

$.get("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+key,window.baidu.sug,'jsonp');

 由于接口返回的是window.baidu.sug({……}),所以本地必须定义一个这样的函数,才能得到跨域请求返回的数据

 //定义回调函数                
 window.baidu = {                    
 	sug: function(data) { 
	 		var results = data.s;
	 		if(results.length == 0){
	 			$('#search-results').hide();
	 		}else{
	 			var html = "";
				for(var i= 0;i<results.length;i++){
					html+="<li>"+results[i]+"</li>";
				}
				$('#search-results ul').html(html);
				$('#search-results').css({
					left:$('#search-form').offset().left,
					top:$('#search-form').offset().top+$('#search-form').height()+10
				}).show();     
	 		}
			                      
 		}
};

3、实现点击关键词是跳转到相应的百度搜索界面

$(document).delegate('li','click', function(){
	var keyword = $(this).text();
	location.href = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&tn=25017023_10_pg&wd="+keyword+"&oq=%25E4%25BD%25A0%25E5%25A5%25BD&rsv_pq=9ec1a62a0001027a&rsv_t=4664T41fswButqvfw6Mc6AbEekGn41Zzz5t%2BzeyhctPdm0DfycU18wvzEStlfgrGBOdgOZo&rqlang=cn&rsv_enter=0&inputT=7590&rsv_sug3=12&rsv_sug1=7&rsv_sug7=100&rsv_sug4=8271";
});

这里使用到了事件代理 

delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。

使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)

(我不太会撰文,直接上代码吧)

代码地址:https://github.com/Steven37/BaiduSearch.git