使用原生js写一个下拉框且可以搜索
时间: 2024-05-12 19:15:38 浏览: 158
原生js下拉菜单带搜索
下面是一个使用原生JS编写的带搜索功能的下拉框代码示例:
HTML:
```html
<div class="dropdown">
<input type="text" id="searchInput" placeholder="Search...">
<button class="dropbtn">Select item</button>
<div class="dropdown-content">
<a href="#">Item 1</a>
<a href="#">Item 2</a>
<a href="#">Item 3</a>
<a href="#">Item 4</a>
<a href="#">Item 5</a>
<a href="#">Item 6</a>
<a href="#">Item 7</a>
<a href="#">Item 8</a>
<a href="#">Item 9</a>
<a href="#">Item 10</a>
</div>
</div>
```
CSS:
```css
.dropdown {
position: relative;
display: inline-block;
}
#searchInput {
padding: 5px;
font-size: 16px;
border: none;
border-bottom: 1px solid #ccc;
}
.dropdown-content {
display: none;
position: absolute;
z-index: 1;
background-color: #f9f9f9;
min-width: 160px;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
.show {
display: block;
}
```
JS:
```javascript
// Get the button and dropdown div
const btn = document.querySelector(".dropbtn");
const dropdown = document.querySelector(".dropdown-content");
// Show/hide dropdown when button is clicked
btn.addEventListener("click", function() {
dropdown.classList.toggle("show");
});
// Search the dropdown when text is entered in the input field
const searchInput = document.getElementById("searchInput");
searchInput.addEventListener("keyup", function(event) {
const filter = event.target.value.toUpperCase();
const items = dropdown.getElementsByTagName("a");
for (let i = 0; i < items.length; i++) {
const txtValue = items[i].textContent || items[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
items[i].style.display = "";
} else {
items[i].style.display = "none";
}
}
});
```
这个下拉框将显示一个输入框和一个按钮。当用户点击按钮时,下拉框中的项目将显示。当用户在输入框中输入文本时,下拉框将根据用户的搜索过滤项目。
阅读全文