本文档详细介绍了如何使用 HTML、CSS 和 JavaScript 创建一个动态可搜索的下拉列表,并实现选中项的显示功能。通过 JSON 数据动态生成下拉选项,并提供搜索过滤功能,最终将用户选择的条目信息展示出来。文章将提供完整的代码示例,并对关键步骤进行详细解释,帮助开发者快速掌握实现方法。
实现步骤
- HTML 结构
首先,我们需要创建一个包含下拉列表的 HTML 结构。这包括一个触发下拉列表显示的按钮和一个用于显示下拉选项的 div 容器。容器内包含一个输入框,用于搜索过滤选项。
<div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <input type="text" placeholder="Search..." id="myInput" onkeyup="filterFunction()"> </div> </div>
- CSS 样式
接下来,我们需要定义 CSS 样式来美化下拉列表,并控制其显示和隐藏。以下是一些关键的样式定义:
#myInput { box-sizing: border-box; background-image: url('searchicon.png'); /* 可选:添加搜索图标 */ background-position: 14px 12px; background-repeat: no-repeat; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; } #myInput:focus { outline: 3px solid #ddd; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; border: 1px solid #ddd; z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover { background-color: #f1f1f1; } .show { display: block; } .dropdown-content > .dropdown-option{ cursor: pointer; } .dropdown-content > .selectedOption{ background-color: darkgray !important; }
- .dropdown:定义下拉列表的容器,使用 position: relative 以便后续的绝对定位。
- .dropdown-content:定义下拉选项的容器,初始状态为 display: none,通过 JavaScript 控制其显示和隐藏。
- .show:用于显示下拉选项,通过 JavaScript 添加到 .dropdown-content 元素上。
- .dropdown-content a:定义下拉选项的样式,包括颜色、内边距、文本修饰等。
- .dropdown-content a:hover:定义鼠标悬停在下拉选项上的样式。
- .dropdown-content > .dropdown-option:定义下拉选项的鼠标指针样式,设置为 pointer
- .dropdown-content > .selectedOption:定义选中下拉选项的背景色,设置为深灰色。
- JavaScript 逻辑
现在,我们需要编写 JavaScript 代码来实现以下功能:
立即学习“Java免费学习笔记(深入)”;
* 从 JSON 数据动态生成下拉选项。 * 实现搜索过滤功能。 * 显示选中的选项。
function myFunction() { var country = [ { "ID": "001", "Country_Name": "India" }, { "ID": "002", "Country_Name": "Australia" }, { "ID": "003", "Country_Name": "Austria" }, { "ID": "004", "Country_Name": "China" }, { "ID": "005", "Country_Name": "Bangladesh" } ]; document.getElementById("myDropdown").classList.toggle("show"); var ele = document.getElementById("myDropdown"); //for each country in the country array for (var i = 0; i < country.length; i++) { //creates an anchor element const countryOption = document.createElement("a"); //holding the country ID in its value attribute countryOption.setAttribute('value', country[i]['ID']); //and the country Name as its innerText countryOption.innerText = country[i]['Country_Name']; //adds the class dropdown-option to the option element countryOption.classList.add('dropdown-option'); //binds the countryOnClick function defined below as its click event handler countryOption.addEventListener('click', countryOnClick); //appends the new anchor to the dropdown element ele.appendChild(countryOption); } } //click event handler for the dropdown options function countryOnClick(event){ //fetch country properties from the element triggering the event const clickedOption = event.target; const countryID = clickedOption.getAttribute('value'); const countryName = clickedOption.innerText; //removes the selectedOption class to every option in the dropdown clickedOption.closest('div').querySelectorAll('.dropdown-option').forEach((o,i)=>{ o.classList.remove('selectedOption'); }); //adds the selectedOption class to the selected option element clickedOption.classList.add('selectedOption'); //show those data on console console.log(`${countryID} - ${countryName}`); console.log( getSelectedOption() ); } function getSelectedOption(){ return document.querySelector('#myDropdown > .dropdown-option.selectedOption'); } //gets called when the filter input changes, and it filters the dropdown options list function filterFunction() { var input, filter, ul, li, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("myDropdown"); a = div.getElementsByTagName("a"); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } }
- myFunction():这个函数负责从 JSON 数据中动态创建下拉选项。它首先获取 JSON 数据,然后遍历数据,为每个选项创建一个 <a> 元素,并设置其 value 属性和文本内容。最后,将这些 <a> 元素添加到下拉列表容器中。
- countryOnClick(event): 这个函数负责处理下拉选项的点击事件。它首先获取被点击的选项的 value 属性和文本内容,然后将选中的选项信息显示在控制台中。
- getSelectedOption(): 这个函数负责获取当前选中的选项。它使用 document.querySelector 方法来查找具有 selectedOption 类的 <a> 元素。
- filterFunction():这个函数负责实现搜索过滤功能。它获取输入框的值,并将其转换为大写。然后,遍历下拉列表中的所有选项,如果选项的文本内容包含输入框的值,则显示该选项,否则隐藏该选项。
注意事项
- 确保 JSON 数据的格式正确。
- 可以根据实际需求修改 CSS 样式。
- 可以根据实际需求修改 JavaScript 代码,例如,将选中的选项信息显示在页面上的某个元素中。
- 为了更好的用户体验,可以添加加载指示器,在数据加载完成之前显示加载状态。
- 在处理大量数据时,可以考虑使用虚拟滚动技术来提高性能。
总结
本文档详细介绍了如何使用 HTML、CSS 和 JavaScript 创建一个动态可搜索的下拉列表,并实现选中项的显示功能。通过 JSON 数据动态生成下拉选项,并提供搜索过滤功能,最终将用户选择的条目信息展示出来。希望本文档能够帮助你快速掌握实现方法。
相关标签:
css javascript java html js json app ssl 点击事件 绝对定位 JavaScript json css html 指针 Event pointer 事件 内边距 display position