模擬百度搜索

通過jsonp的跨域,實現對百度搜索接口的調用,最終實現模擬搜索的功能。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .block{
            width: 700px;
            height: 50px;
            border: 1px solid black;
            margin: 100px auto;
        }
        .res{
            width: 570px;
            height: 50px;
            border-style: none;
            outline: none;
            box-sizing: border-box;
            font-size: 20px;
            float: left;
            padding-left: 20px;
        }
        .btn{
            display: block;
            width: 130px;
            height: 50px;
            background-color: #2ac9ff;
            text-align: center;
            line-height: 50px;
            color: white;
            font-size: 20px;
            float: left;
            cursor: pointer;
        }
        .btn:hover{
            background-color: #2eaaff;
        }
        .menu{
            margin: 0;
            padding: 0;
            border: 1px solid silver;
            width: 570px;
            margin-left: -1px;
        }
        .menu>li{
            list-style: none;
            line-height: 30px;
            font-size: 16px;
            padding-left: 10px;
            cursor: pointer;
            font-weight: bold;
        }
        .menu>li>a{
            color: black;
            text-decoration: none;
        }
        .menu>li:hover{
            background-color: #eaeaea;
        }
    </style>
</head>
<body>
<div class="block">
    <input class="res" type="text"/>
    <span class="btn">百度一下</span>
</div>
<script>
    var result=document.getElementsByClassName("res")[0];
    var block=document.getElementsByClassName("block")[0];
    var btn=document.getElementsByClassName("btn")[0];
    result.οnkeyup=function (e){
        var value=this.value;
        var sc=document.createElement("script");
        sc.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+value+"&cb=shoData";
        document.body.appendChild(sc);
        sc.remove();
    }
    function shoData(data){
        var menu=document.getElementsByClassName("menu")[0];
        if(menu)
        {
            menu.remove();
        }
        var ul=document.createElement("ul");
        ul.className="menu";
        for(var i=0;i<data.s.length;i++)
        {
            var li=document.createElement("li");
            li.innerHTML="<a href='https://www.baidu.com/s?wd="+data.s[i]+"'>"+data.s[i]+"</a>";
            /*li.addEventListener("click",clickMenu);*/
            ul.appendChild(li);
        }
        block.appendChild(ul);
    }
    btn.οnclick=function (){
        location.href="https://www.baidu.com/s?wd="+result.value;
    }
   /* function clickMenu(){
        /!*location.href="https://www.baidu.com/s?wd="+this.innerHTML;*!/
    }*/
</script>
</body>
</html>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章