js模糊查詢select內容并生成下拉框點選
當前位置:點晴教程→知識管理交流
→『 技術文檔交流 』
![]() ![]() <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>模糊查詢示例</title> <style> #dropdown { display: none; border: 1px solid #ccc; max-height: 150px; overflow-y: auto; position: absolute; background: white; z-index: 1000; } .dropdown-item { padding: 8px; cursor: pointer; text-align: left; } .dropdown-item:hover { background-color: #f0f0f0; } </style> </head> <body> <input type="text" id="searchInput" placeholder="請輸入關鍵詞..." autocomplete="off"> <div id="dropdown" style="width:200px;"></div> <select id="originalSelect"> <option value="apple">蘋果</option> <option value="banana">香蕉</option> <option value="grape">葡萄</option> <option value="orange">橙子</option> <option value="strawberry">草莓</option> </select> <script> document.getElementById('searchInput').addEventListener('input', function() { const query = this.value.toLowerCase(); const dropdown = document.getElementById('dropdown'); const originalSelect = document.getElementById('originalSelect'); dropdown.innerHTML = ''; if (query) { dropdown.style.display = 'block'; Array.from(originalSelect.options).forEach(option => { if (option.text.toLowerCase().includes(query)) { const div = document.createElement('div'); div.textContent = option.text; div.className = 'dropdown-item'; div.onclick = function() { document.getElementById('searchInput').value = option.text; option.selected=true;// 賦值給輸入框 originalSelect.onchange(); dropdown.style.display = 'none'; // 隱藏下拉框 }; dropdown.appendChild(div); } }); } else { dropdown.style.display = 'none'; } }); document.addEventListener('click', function(event) { const dropdown = document.getElementById('dropdown'); if (!document.getElementById('searchInput').contains(event.target)) { dropdown.style.display = 'none'; } }); </script> </body> </html> 該文章在 2025/1/22 11:49:08 編輯過 |
關鍵字查詢
相關文章
正在查詢... |