本章节我们将学习如何使用 JS/CSS 实现下拉菜单搜索或过滤功能。
先看下效果如下:
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">下拉菜单</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
<a href="#about">Google</a>
<a href="#base">Runoob</a>
<a href="#blog">Taobao</a>
<a href="#contact">Wiki</a>
<a href="#custom">Zhihu</a>
<a href="#support">Tmall</a>
<a href="#tools">Weibo</a>
</div>
</div>
以下搜索搜索框和联想菜单的样式:
/* 下拉菜单按钮 */
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* 鼠标移动到下拉菜单按钮到样式*/
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
/* 搜索框 */
#myInput {
box-sizing: border-box;
background-image: url('searchicon.png');
background-position: 14px 12px;
background-repeat: no-repeat;
font-size: 16px;
padding: 14px 20px 12px 45px;
border: none;
border-bottom: 1px solid #ddd;
}
/* 搜索框获取焦点的样式 */
#myInput:focus {outline: 3px solid #ddd;}
/* 容器 <div> - 定位下拉菜单 */
.dropdown {
position: relative;
display: inline-block;
}
/* 下拉菜单内容 (默认隐藏) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f6f6f6;
min-width: 230px;
border: 1px solid #ddd;
z-index: 1;
}
/* 下拉菜单链接样式 */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* 鼠标移动到链接上的样式 */
.dropdown-content a:hover {background-color: #f1f1f1}
/* 显示下拉菜单 (使用 JS 添加 .dropdown-content 类) */
.show {display:block;}
以下是搜索搜索框和联想菜单的 JavaScript 代码:
/* 点击按钮设置下拉菜单的显示与隐藏 */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
/* 搜索功能 */
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
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";
}
}
}