js实现带菜单栏目搜索的下拉菜单
人气:0在下拉菜单栏目比较多的时候,用户查找栏目阅读会很麻烦,为了提高用户体验度,加个栏目搜索会很方便。这篇文章主要介绍了js实现带菜单栏目搜索的下拉菜单,感觉挺实用的,需要的朋友可以参考下
js实现带搜索的下拉菜单 — 基础 HTML 代码
<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" rel="external nofollow" >Google</a> <a href="#base" rel="external nofollow" >Runoob</a> <a href="#blog" rel="external nofollow" >Taobao</a> <a href="#contact" rel="external nofollow" >Wiki</a> <a href="#custom" rel="external nofollow" >Zhihu</a> <a href="#support" rel="external nofollow" >Tmall</a> <a href="#tools" rel="external nofollow" >Weibo</a> </div> </div>
js实现带搜索的下拉菜单 — 菜单的样式:
/* 下拉菜单按钮 */ .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;}
js实现带搜索的下拉菜单 — 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"; } } }
加载全部内容