html如何制作一个搜索框

form {
display: flex;
justify-content: center;
margin-top: 20px;
}
input[type="text"] {
width: 300px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 10px;
}
button {
padding: 10px 20px;
border: none;
background-color: #007BFF;
color: white;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 8px;
border-bottom: 1px solid #ccc;
}
.suggestions {
border: 1px solid #ccc;
border-top: none;
max-height: 150px;
overflow-y: auto;
position: absolute;
background: white;
z-index: 1000;
width: 300px;
}
.suggestions li {
padding: 8px;
cursor: pointer;
}
.suggestions li:hover {
background-color: #f0f0f0;
}
- Apple
- Banana
- Cherry
- Date
- Elderberry
- Fig
- Grape
const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry', 'Fig', 'Grape'];
function filterList() {
const query = document.getElementById('search').value.toLowerCase();
const listItems = document.querySelectorAll('#list li');
listItems.forEach(item => {
if (item.textContent.toLowerCase().includes(query)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
}
function showSuggestions() {
const query = document.getElementById('search').value.toLowerCase();
const suggestions = document.getElementById('suggestions');
suggestions.innerHTML = '';
if (query) {
const filteredItems = items.filter(item => item.toLowerCase().includes(query));
filteredItems.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
li.onclick = () => {
document.getElementById('search').value = item;
suggestions.style.display = 'none';
};
suggestions.appendChild(li);
});
suggestions.style.display = 'block';
} else {
suggestions.style.display = 'none';
}
}