用js+html+css写出一个百度搜索框要有下拉菜单
时间: 2024-01-15 11:04:35 浏览: 72
HTML+CSS3+JS 实现的下拉菜单
好的,下面是一个简单的实现:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>百度搜索框</title>
<style>
#search-container {
position: relative;
display: inline-block;
}
#search-input {
padding: 10px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
outline: none;
}
#search-dropdown {
position: absolute;
top: 40px;
left: 0;
z-index: 1;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
display: none;
}
#search-dropdown ul {
list-style: none;
margin: 0;
padding: 0;
}
#search-dropdown li {
padding: 5px 10px;
cursor: pointer;
}
#search-dropdown li:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="search-container">
<input type="text" id="search-input" placeholder="请输入搜索内容">
<div id="search-dropdown"></div>
</div>
<script>
const searchInput = document.getElementById("search-input");
const searchDropdown = document.getElementById("search-dropdown");
searchInput.addEventListener("input", function() {
// 发送请求获取下拉菜单内容,这里用假数据代替
const data = ["百度一下", "百度翻译", "百度知道", "百度贴吧", "百度文库", "百度地图"];
// 清空下拉菜单
searchDropdown.innerHTML = "";
if (this.value) {
// 根据输入内容生成下拉菜单
data.filter(item => item.includes(this.value)).forEach(item => {
const li = document.createElement("li");
li.innerHTML = item;
li.addEventListener("click", function() {
searchInput.value = item;
searchDropdown.style.display = "none";
});
searchDropdown.appendChild(li);
});
searchDropdown.style.display = "block";
} else {
searchDropdown.style.display = "none";
}
});
</script>
</body>
</html>
```
这个实现包含一个输入框和一个下拉菜单,当输入框中有内容时,会根据输入内容生成下拉菜单。用户可以通过鼠标点击下拉菜单中的选项来选择搜索内容。
阅读全文