input搜索提示功能--基于jquery框架

来源:互联网 发布:逻辑推理软件 编辑:程序博客网 时间:2024/06/05 04:56

因需求,网站需要一个搜索提示功能,本想用html5原生控件实现,
但部分浏览器兼容性不好,最后还是自己用jquery实现功能。


效果图

效果图

Html代码

<section class="search">    <div class="row">        <input type="text" placeholder="搜索" id="Search" name="search">    </div></section>

CSS样式

     .search{            width: 200px;            position: fixed;            z-index: 2;            margin: auto;            bottom: 0;            right: 0;            left: 0;            top: 200px;        }        .search input{            width: 200px;            border: none;            border: solid 1px #00a0e9;            height: 20px;            padding-left: 15px;        }        .search input,.search button:focus{            outline: none;        }        .search button{            width: 20px;            background: #00a0e9;            border: none;            height: 20px;        }        table{            position: absolute;            left: 0;            width:  215px;            border: solid 1px #e0e0e0;        }        table td{            height: 0.6rem;            padding-left: 15px;        }

核心Javascript

//执行代码window.onload = ListenerSearch();//实时监控搜索框文本输入事件function ListenerSearch(){    var name = ['1','2','33','41','15','董秘课堂','董秘资料'];    //实时监控文本输入    $("input[name='search']").bind('input propertychange',function () {        QueryKeyword($(this).val(),name);    });}//检索数组里是否有对应关键词function QueryKeyword(SearchName,ArrayList) {    //初始化数组    var Keyword = [];    //遍历数组内容    for(var i = 0; i < ArrayList.length; i++){        //查询判断数组内是否包含关键词        if(SearchName.length != 0){            //搜索框输入数据全等于数组内字符串参数            if(SearchName === ArrayList[i].substr(0,SearchName.length)){                //添加数据                Keyword.push(ArrayList[i]);            }        }    }    if(Keyword.length != 0){        //创建table表单        CreateTable(Keyword);    } else {        //删除table表单        RemoveTable();    }}//监控table表单点击事件,修改input内容function TableOnclick(id) {    $("#Search").val($("#"+id).html());    $("#Table").remove();}//创建table表单function CreateTable(Keyword) {    var TableContent = "";    for(var i = 0; i < Keyword.length; i++){        TableContent += "" +            "<tr>" +            "<td id='"+i+"' onclick='TableOnclick(this.id)'>"+Keyword[i]+"</td>" +            "</tr>";    }    //table表单不存在时进行创建    if(!document.getElementById("#Table")){        var Table = document.createElement('table');        Table.id = "Table";        $(".search").append(Table);    }    $("#Table").html(TableContent);}//删除table表单function RemoveTable() {    $("#Table").remove();}

注意:以上代码只是通过静态数组进行交互,若想动态交互,将ListenerSearch()函数下的name参数改成通过ajax取得的数组参数即可。

浏览器兼容

  1. 目前,还没测试兼容浏览器,若有问题,还请在留言处提出。