下拉框可搜索(Searchable Dropdown)是一种常见的用户界面组件,它允许用户在输入框中键入文本时实时过滤下拉列表中的选项。这种组件在前端开发中非常实用,可以提高用户体验,尤其是在选项较多的情况下。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Searchable Dropdown</title>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.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 a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #f1f1f1}
.dropdown input[type="text"] {
width: 100%;
box-sizing: border-box;
}
.show {display: block;}
</style>
</head>
<body>
<div class="dropdown">
<input type="text" id="searchInput" onkeyup="filterFunction()" placeholder="Search...">
<div class="dropdown-content" id="dropdownContent">
<a href="#">Apple</a>
<a href="#">Banana</a>
<a href="#">Cherry</a>
<a href="#">Date</a>
<a href="#">Elderberry</a>
</div>
</div>
<script>
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("searchInput");
filter = input.value.toUpperCase();
div = document.getElementById("dropdownContent");
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";
}
}
}
</script>
</body>
</html>
对于远程搜索,可以使用fetch
或axios
等库从服务器获取数据,并在前端进行显示。以下是一个简要的示例:
async function fetchOptions(searchTerm) {
const response = await fetch(`/api/search?term=${searchTerm}`);
const data = await response.json();
updateDropdown(data);
}
function updateDropdown(options) {
const dropdownContent = document.getElementById("dropdownContent");
dropdownContent.innerHTML = "";
options.forEach(option => {
const a = document.createElement("a");
a.href = "#";
a.textContent = option;
dropdownContent.appendChild(a);
});
}
通过这种方式,可以处理大量数据,提高搜索性能。
领取专属 10元无门槛券
手把手带您无忧上云