
使用 HTML, CSS 和 JavaScript 显示下拉列表中选中的项目
本文详细介绍了如何使用 HTML, CSS 和 JavaScript 创建一个动态下拉列表,该列表从 JSON 数组中获取数据,并允许用户搜索和选择项目。文章重点讲解了如何捕获用户选择的项目,并将其显示在页面上,同时提供代码示例和注意事项,帮助开发者快速实现该功能。
HTML 结构
首先,我们需要定义 HTML 结构来创建下拉列表。以下代码展示了一个基本的下拉列表结构,包含一个按钮用于触发下拉列表的显示,一个输入框用于搜索,以及一个用于显示列表项的 div 元素。
CSS 样式
立即学习“Java免费学习笔记(深入)”;
接下来,我们需要使用 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;
cursor: pointer; /* 添加鼠标悬停样式 */
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
.show {
display: block;
}
.dropdown-content > .dropdown-option{
cursor: pointer;
}
.dropdown-content > .selectedOption{
background-color: darkgray !important;
}JavaScript 逻辑
现在,我们需要使用 JavaScript 来实现下拉列表的动态功能。以下代码展示了如何从 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" }
];
var dropdown = document.getElementById("myDropdown");
dropdown.classList.toggle("show");
dropdown.innerHTML = ''; // Clear existing content
// Add search input
let input = document.createElement('input');
input.type = 'text';
input.placeholder = 'Search...';
input.id = 'myInput';
input.onkeyup = filterFunction;
dropdown.appendChild(input);
// Populate dropdown with country options
for (var i = 0; i < country.length; i++) {
const countryOption = document.createElement("a");
countryOption.setAttribute('value', country[i]['ID']);
countryOption.innerText = country[i]['Country_Name'];
countryOption.classList.add('dropdown-option');
countryOption.addEventListener('click', countryOnClick);
dropdown.appendChild(countryOption);
}
}
function countryOnClick(event) {
const clickedOption = event.target;
const countryID = clickedOption.getAttribute('value');
const countryName = clickedOption.innerText;
// Remove selectedOption class from all options
clickedOption.closest('div').querySelectorAll('.dropdown-option').forEach((o, i) => {
o.classList.remove('selectedOption');
});
// Add selectedOption class to the selected option
clickedOption.classList.add('selectedOption');
// Log selected country details
console.log(`${countryID} - ${countryName}`);
console.log(getSelectedOption());
// You can further update the UI to display the selected country
// For example, update a element with id 'selectedCountry'
// document.getElementById('selectedCountry').innerText = countryName;
}
function getSelectedOption() {
return document.querySelector('#myDropdown > .dropdown-option.selectedOption');
}
function filterFunction() {
var input, filter, 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 数组中获取国家数据,然后动态生成列表项,并将其添加到 myDropdown 元素中。此外,它还动态创建搜索框。
- countryOnClick(event): 这个函数处理列表项的点击事件。当用户点击一个列表项时,该函数会获取选中的国家 ID 和名称,并将其显示在控制台中。你可以根据实际需求修改该函数,例如将选中的国家显示在页面上的某个元素中。该函数还负责更新选中项的样式。
- getSelectedOption(): 返回当前选中的元素。
- filterFunction(): 这个函数负责实现搜索功能。当用户在搜索框中输入内容时,该函数会根据输入的内容过滤列表项,只显示包含输入内容的列表项。
注意事项:
- 确保 JSON 数组中的数据格式正确,并且包含 ID 和 Country_Name 字段。
- 可以根据实际需求修改 CSS 样式,以美化下拉列表的外观。
- 可以根据实际需求修改 JavaScript 代码,以实现更复杂的功能,例如多选、自动完成等。
- 为了更好的用户体验,可以添加加载状态,在数据加载完成之前显示加载动画。
- 在countryOnClick函数中,可以根据实际需求更新UI,例如将选中的国家显示在页面上。
总结:
本文详细介绍了如何使用 HTML, CSS 和 JavaScript 创建一个动态下拉列表,并实现搜索和选择功能。通过本文的学习,你可以快速创建一个功能完善的下拉列表,并将其应用到你的项目中。 记住,代码只是一个起点,根据你的具体需求进行修改和扩展才是关键。











