在JavaScript中实现下拉列表的搜索功能,通常涉及到HTML、CSS和JavaScript的基本知识。下面我会给出一个简单的示例,展示如何创建一个可搜索的下拉列表。
<div class="searchable-dropdown">
<input type="text" placeholder="Search..." id="dropdown-search"/>
<div class="dropdown-content" id="dropdown-content">
<div class="dropdown-item">Apple</div>
<div class="dropdown-item">Banana</div>
<div class="dropdown-item">Cherry</div>
<div class="dropdown-item">Date</div>
<div class="dropdown-item">Elderberry</div>
</div>
</div>
.searchable-dropdown {
position: relative;
display: inline-block;
}
#dropdown-search {
width: 200px;
box-sizing: border-box;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content .dropdown-item {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content .dropdown-item:hover {
background-color: #f1f1f1;
}
.searchable-dropdown.show .dropdown-content {
display: block;
}
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('dropdown-search');
const dropdown = document.querySelector('.searchable-dropdown');
const dropdownContent = document.getElementById('dropdown-content');
const dropdownItems = dropdownContent.getElementsByClassName('dropdown-item');
searchInput.addEventListener('keyup', function() {
const filter = searchInput.value.toLowerCase();
let visibleItems = 0;
for (let i = 0; i < dropdownItems.length; i++) {
const item = dropdownItems[i];
if (item.textContent.toLowerCase().indexOf(filter) > -1) {
item.style.display = '';
visibleItems++;
} else {
item.style.display = 'none';
}
}
// Show or hide the dropdown based on the number of visible items
if (visibleItems > 0) {
dropdown.classList.add('show');
} else {
dropdown.classList.remove('show');
}
});
// Toggle the dropdown visibility when clicking on the input field
searchInput.addEventListener('click', function() {
dropdown.classList.toggle('show');
});
// Close the dropdown when clicking outside of it
window.addEventListener('click', function(event) {
if (!event.target.matches('#dropdown-search')) {
dropdown.classList.remove('show');
}
});
});
keyup
事件,根据输入内容过滤下拉列表中的项。这种可搜索的下拉列表在需要用户从大量选项中快速选择时非常有用,例如:
通过上述代码和解释,你应该能够实现一个基本的可搜索下拉列表,并根据需要进行扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云