如何使用 CSS 和 JavaScript 搜索下拉菜单中的项目?

cssweb developmentfront end technologyjavascript

要使用 CSS 和 JavaScript 搜索下拉菜单中的项目,代码如下 −

示例

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   .dropbtn {
      background-color: rgb(76, 78, 175);
      color: white;
      padding: 16px;
      font-size: 16px;
      border: none;
      cursor: pointer;
   }
   .dropbtn:hover, .dropbtn:focus {
      background-color: #4f3e8e;
   }
   .searchField {
      box-sizing: border-box;
      font-size: 16px;
      padding: 14px 20px 12px 45px;
      border: none;
      border-bottom: 1px solid #ddd;
   }
   .searchField:focus {outline: 3px solid #ddd;}
   .dropdown {
      position: relative;
      display: inline-block;
   }
   .dropdownList {
      display: none;
      position: absolute;
      background-color: #f6f6f6;
      min-width: 230px;
      overflow: auto;
      border: 1px solid #ddd;
      z-index: 1;
   }
   .dropdownList a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
   }
   .dropdown a:hover {background-color: #ddd;}
   .show {display: block;}
</style>
</head>
<body>
<h1>Search/filterText Dropdown Example</h1>
<div class="dropdown">
<button class="dropbtn" onclick="showDropList()">Dropdown</button>
<div id="myDropdown" class="dropdownList">
<input type="text" placeholder="Search.." class="searchField">
<a href="#">Cow</a>
<a href="#">Cat</a>
<a href="#">Dog</a>
<a href="#">Giraffe</a>
<a href="#">Lion</a>
<a href="#">Leopard</a>
<a href="#">Cheetah</a>
</div>
</div>
<script>
   function showDropList(){
      let dropDiv = document.querySelector('.dropdownList');
      if(dropDiv.style.display==="block"){
         dropDiv.style.display = "";
      } else {
         dropDiv.style.display = "block";
      }
   }
   document.querySelector('.searchField').addEventListener('keyup',filterDropdown);
   function filterDropdown() {
      var inputSearch, filterText, ul, li, links, i,div;
      inputSearch = document.querySelector(".searchField");
      filterText = inputSearch.value.toUpperCase();
      div = document.getElementById("myDropdown");
      links = div.getElementsByTagName("a");
      for (i = 0; i < links.length; i++) {
         txtValue = links[i].textContent || links[i].innerText;
         if (txtValue.toUpperCase().indexOf(filterText) > -1) {
            links[i].style.display = "";
         } else {
         links[i].style.display = "none";
         }
      }
   }
</script>
</body>
</html>

输出

上述代码将产生以下输出 −

点击下拉按钮并在搜索字段中输入文本 −


相关文章