js实现搜索提示框效果

时间:2021-05-26

本文实例为大家分享了js实现搜索提示框效果的具体代码,供大家参考,具体内容如下

首先写静态页面

<div class="container"> <!-- 搜索框 --> <input type="text" id="search" /> <!-- 动态提示的数据框liebia --> <div id="alert"> <ul></ul> </div></div>

CSS样式

* { margin: 0; padding: 0;}html,body { background: darkgray;}.container { position: absolute; left: 50%; top: 50px; transform: translateX(-50%);}#search { width: 300px; height: 50px; padding-left: 10px; border-radius: 5px; border: none; outline: none;}#alert { width: 312px; position: relative; left: -1px; display: none; }#alert > ul { list-style: none; margin: 0; padding: 0;}#alert > ul > li { border: 0.5px solid #000; height: 40px; line-height: 40px; padding-left: 10px; border-radius: 5px; background: #fff;}#alert > ul:last-child { border-bottom: 1px solid #000;}

JS代码

var $search = $("#search");var $alert = $("#alert");var $alertUl = $("#alert>ul");// 清空列表的方法function clearUl() { $alertUl.empty();}$search .bind("input", function () { // 清空列表 clearUl(); // 获取到用户所输入的内容 var value = $(this).val(); // console.log(value); // 使用getJSON方法获取json数据 $.getJSON("data/server4.json", function (data) { // console.log(data); // 获取到json数据中的name值 $.each(data, function (input, obj) { // console.log(obj); var name = obj.name; // console.log(name); if (name.indexOf(value) >= 0) { // 表示输入的内容在name中存在 var valueArr = obj.value; // console.log(valueArr); $.each(valueArr, function (input, text) { // console.log(text); // 将数据添加到HTML页面 $alertUl.append(`<li>${text}</li>`); }); } }); }); // 将ul列表显示出来 $alert.css("display", "block");}) .bind("blur", function () { $alert.css("display", "none");});

实现效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章