<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
width: 100%;
}
#txt {
width: 400px;
height: 30px;
}
#list{
width: 402px;
border:1px solid #ccc ;
border-top:0;
display: none;
}
#list li{
list-style: none;
width: 100%;
height: 25px;
font-size: 14px;
font-family: "微软雅黑";
line-height: 25px;
}
#list li a{
text-decoration: none;
color: #ccc;
display: block;
width: 100%;
height: 25px;
}
#list li a:hover{
background: pink;
color: #fff;
}
#list li a.active{
background: cornflowerblue;
color: red;
}
#box{
width:500px ;
margin: 100px auto;
position: relative;
}
#btn{
display: block;
width: 100px;
height: 34px;
background: cornflowerblue;
color: #fff;
position: absolute;
left:404px;
top: 0;
text-align: center;
line-height: 34px;
font-size: 14px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<input type="text" name="txt" id="txt" value="" />
<span id="btn">
百度一下
</span>
<ul id="list">
</ul>
</div>
<script type="text/javascript">
var oTxt = document.getElementById("txt");
var oUl = document.getElementById("list");
var oLi = oUl.getElementsByTagName('li');
var oA = oUl.getElementsByTagName('a');
var oBtn = document.getElementById("btn");
var index = -1;
oTxt.onfocus = function(){
oTxt.onkeyup = function(ev){
ev = ev||event;
if( ev.keyCode == '40' ){
for(var i = 0;i < oA.length;i++){ //***清空其他的***
oA[i].className = '';
}
index++;
if(index > oA.length-1){
index = 0;
}
oA[index].className = 'active';
oTxt.value = oA[index].innerHTML;
oTxt.onclick = function(){
create();
index =-1;
}
}else if(ev.keyCode == '38'){
for(var i = 0;i < oA.length;i++){
oA[i].className = '';
}
index--;
if(index < 0){
index = oA.length-1;
}
oA[index].className = 'active';
oTxt.value = oA[index].innerHTML;
oTxt.onclick = function(){
create();
index =-1;
}
}else if(ev.keyCode == '13'){
if(index == -1){
open('https:www.baidu.com/s?wd='+oTxt.value,'_blank');
}else{
open(oA[index],'_blank');
}
}
else{
create();
}
oBtn.onclick = function(){
open('https:www.baidu.com/s?wd='+oTxt.value,'_blank');
}
}
}
//创建script
function create(){
var val = oTxt.value;
var oScript = document.createElement('script');
/*内容就是一个函数调用*/
//相当于fn(data)调用,此时的src是跨域的地址:
//search({q:"\' val \'",p:false,s:["valentino","valid","validate","value","validation","valve","valak","valar morghulis","valgrind","validity"]});
oScript.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+val+'&cb=search';
document.body.appendChild( oScript );
document.body.removeChild( oScript );
}
function search( data ){ //相当于fn(){}定义
var str = '';
for( var i=0;i < data.s.length; i++){
str += '<li><a href="https://www.baidu.com/s?wd='+data.s[i]+'" target="_blank">'+data.s[i]+'</a></li>';
}
oUl.innerHTML = str;
oUl.style.display = 'block';
}
</script>
</body>
</html>