Js之模拟百度搜索框

来源:互联网 发布:整理桌面的软件 编辑:程序博客网 时间:2024/05/20 13:19

在这里我们只是简单的用数组模拟了一下数据库中的数据

html代码如下:

<div class="box" id="box">       <input type="text" name="content" class="content" id="txt"/>       <button>搜索</button>       <!--<div class="pop" id="pop">           <ul>               <li>a</li>               <li>aaa</li>               <li>aaaa</li>           </ul>        </div>--></div>

css样式:

<style>    .box{        width: 650px;        height: 400px;        /*border: 1px solid gray;*/        margin:100px auto;    }    .content{        width: 486px;        height: 30px;        float: left;        padding-left:10px;    }    button{        width: 80px;        height: 35px;        float: left;        margin-left:20px;        font-size:18px;    }    #pop{        margin-top:0;        width: 498px;        height: 300px;        border: 1px solid gray;        border-top:0;        float: left;    }    ul{        list-style: none;        margin:0;        padding:0;    }    ul li{        margin-left:10px;        margin-top:10px;        cursor: pointer;        height: 30px;        line-height:30px;    }    ul li:hover{        background-color: gray;    }</style>

js代码如下:

<script>    //获取输入框    var txt = document.getElementById("txt");    var arr = ["今晚吃鸡","泪点","画画","evan","evan_qb","evanevan"];    var box = document.getElementById("box");    //输入文字    txt.onkeyup = function(){        //判断当前值是否是已经存储数据的开头        var arr2 = [];        for(var i = 0;i<arr.length;i++){            if (arr[i].indexOf(this.value) === 0){                arr2.push(arr[i]);            }        }        //获取pop        var pop = document.getElementById("pop");        //如果输入的值为空        if(this.value.length === 0){            if (pop){                box.removeChild(pop);            }            return;        }        //不满足的情况        // 如果已经存在则先删除        if (pop){            box.removeChild(pop);        }        //如果arr2的长度为0        if(arr2.length === 0){            return;        }        //创建盒子        var div = document.createElement("div");        div.id = "pop";//        div.className = "pop";        box.appendChild(div);        //创建ul        var ul = document.createElement("ul");        div.appendChild(ul);        //将数组arr2的数据显示出来        for (var i = 0;i<arr2.length;i++){            var li = document.createElement("li");            li.innerHTML = arr2[i];            ul.appendChild(li);        }    }    txt.onblur = function(){        box.removeChild(pop);    }</script>


运行结果如下: