Js之模拟百度搜索框

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

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>


运行结果如下:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值