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>
출력
위의 코드는 다음 출력을 생성합니다 -
드롭다운 버튼을 클릭하고 검색 필드에 텍스트를 입력할 때 -