要实现一个带搜索功能的下拉框,可以使用JavaScript结合HTML和CSS来完成。以下是一个简单的示例,展示了如何实现这一功能:
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="searchable-dropdown">
<input type="text" id="searchInput" placeholder="Search...">
<div id="dropdown" class="dropdown-content"></div>
</div>
<script src="script.js"></script>
</body>
</html>
.searchable-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 div {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content div:hover {background-color: #f1f1f1}
const data = [
"Apple", "Banana", "Cherry", "Date", "Elderberry",
"Fig", "Grape", "Honeydew", "Kiwi", "Lemon"
];
const searchInput = document.getElementById('searchInput');
const dropdown = document.getElementById('dropdown');
searchInput.addEventListener('input', function() {
const searchValue = this.value.toLowerCase();
dropdown.innerHTML = '';
if (searchValue.length > 0) {
const filteredData = data.filter(item => item.toLowerCase().includes(searchValue));
filteredData.forEach(item => {
const div = document.createElement('div');
div.textContent = item;
div.addEventListener('click', function() {
searchInput.value = item;
dropdown.style.display = 'none';
});
dropdown.appendChild(div);
});
dropdown.style.display = 'block';
} else {
dropdown.style.display = 'none';
}
});
document.addEventListener('click', function(event) {
if (!event.target.closest('.searchable-dropdown')) {
dropdown.style.display = 'none';
}
});
通过上述代码和解释,你应该能够实现一个基本的带搜索功能的下拉框,并理解其背后的原理和应用场景。
企业创新在线学堂
Elastic 实战工作坊
Elastic 实战工作坊
云+社区沙龙online第5期[架构演进]
Elastic 实战工作坊
云+社区沙龙online [云原生技术实践]
云+社区沙龙online第6期[开源之道]
领取专属 10元无门槛券
手把手带您无忧上云