<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>search</title>
<style type="text/css" media="screen">
* {
margin: 0;
padding: 0;
}
li {
list-style: none;
padding: 3px;
}
#searchMsg{
width: 540px;
height: 34px;
vertical-align: top;
font-size: 14px;
padding-left: 3px;
}
li:hover {
background-color: rgb(168, 213, 252);
cursor: default;
}
ul li:first-child{
margin-top: 0;
}
ul{
border: 1px solid #b6b6b6;
border-top: 0px;
display: none;
}
#btn{
color: #fff;
line-height: 38px;
padding: 0 8px;
font-size:14px;
display: inline-block;
height: 38px;
background: #3385ff;
cursor: pointer;
}
.searchbar{
font-size: 0;
}
.search{
position: fixed;
left: 50%;
top: 50%;
margin-left: -308px;
margin-top: -124px;
}
</style>
</head>
<body>
<div class="search">
<div class="searchbar">
<input type="text" id="searchMsg">
<span id="btn">百度一下</span>
</div>
<ul id="list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script>
var searchMsg = document.getElementById("searchMsg");
var list = document.getElementById("list");
var btn = document.getElementById("btn");
//监听输入框的keuup事件,
searchMsg.onkeyup = function() {
if (this.value) {
show(list);
// 动态创建script标签,使用百度提供的接口,将查询字符串编码后,写到src当中
var s = document.createElement('script');
s.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + encodeURI(this.value.trim()) + '&json=1&p=3&sid=1457_21105_17001_22158&req=2&csor=1&pwd=7&cb=fn';
// 插入到文档后获取jsonp格式的数据,然后调用callback函数,将data数据以参数的形式传入
document.body.appendChild(s);
} else {
hide(list);
}
}
//点击li标签后把输入框的信息填入到文本框
list.onclick = function(e) {
var e = e || window.event;
var target = e.target || e.srcElement;
if (target.nodeName == "LI") {
searchMsg.value = target.innerHTML;
}
hide(list)
}
//点击百度一下按钮跳转到相应的页面
btn.onclick = function() {
location.href = "http://www.baidu.com/s?wd=" + searchMsg.value
}
function fn(data) {
var lis = document.querySelectorAll('li');
//这时候遍历查询到的信息,放到li标签当中
data.s.forEach(function(item, index) {
lis[index].innerHTML = item;
});
// 获取到数据后,把脚本删除
var s = document.querySelectorAll('script');
for (var i = 1, len = s.length; i < len; i++) {
document.body.removeChild(s[i]);
}
}
function hide(obj) {
obj.style.display = "none"
}
function show(obj) {
obj.style.display = "block"
}
</script>
</body>
</html>
百度页面
最新推荐文章于 2024-08-12 07:54:21 发布