<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Dropdown</title>
<style>
.custom-dropdown {
position: relative;
display: inline-block;
}
.custom-dropdown input[type="text"] {
width: 200px;
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
.custom-dropdown .dropdown-content {
display: none;
position: absolute;
">#f9f9f9;
width: 200px;
max-height: 200px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
z-index: 1;
}
.custom-dropdown .dropdown-content a {
display: block;
padding: 10px;
text-decoration: none;
color: #333;
}
.custom-dropdown .dropdown-content a:hover {
">#ddd;
}
</style>
</head>
<body>
<div class="custom-dropdown">
<input type="text" id="ssid" placeholder="请输入WIFI名称...">
<div class="dropdown-content" id="myDropdown">
<a href="#">ddddOption 1</a>
<a href="#">sssOption 2</a>
<a href="#">gggOption 3</a>
<a href="#">aaaOption 4</a>
<a href="#">bbOption 5</a>
</div>
</div>
<script>
// 显示下拉列表
function showDropdown() {
var dropdown = document.getElementById("myDropdown");
dropdown.style.display = "block";
}
// 隐藏下拉列表
function hideDropdown() {
var dropdown = document.getElementById("myDropdown");
dropdown.style.display = "none";
}
// 根据输入内容过滤选项
function filterOptions() {
var input = document.getElementById("ssid");
var filter = input.value.toLowerCase();
var options = document.getElementById("myDropdown").getElementsByTagName("a");
for (var i = 0; i < options.length; i++) {
var txtValue = options[i].textContent || options[i].innerText;
if (txtValue.toLowerCase().indexOf(filter) > -1) {
options[i].style.display = "";
} else {
options[i].style.display = "none";
}
}
}
// 选中下拉框选项并填入输入框
function selectOption(option) {
var input = document.getElementById("ssid");
input.value = option.textContent.trim();
hideDropdown(); // 选中后隐藏下拉列表
}
// 添加事件监听器
document.getElementById("ssid").addEventListener("focus", showDropdown);
document.getElementById("ssid").addEventListener("input", function() {
showDropdown();
filterOptions();
});
// document.getElementById("ssid").addEventListener("blur", hideDropdown);
document.getElementById("ssid").addEventListener("focusout", function(event) {
if (!event.relatedTarget || !event.relatedTarget.closest("#myDropdown")) {
hideDropdown();
}
});
// 给每个下拉框选项添加点击事件
var options = document.getElementById("myDropdown").getElementsByTagName("a");
for (var i = 0; i < options.length; i++) {
options[i].addEventListener("click", function() {
selectOption(this);
});
}
</script>
</body>
</html>