原生js实现下拉框,支持多选、搜索
warning:
这篇文章距离上次修改已过223天,其中的内容可能已经有所变动。
以下是一个使用原生JavaScript实现的简单下拉框,支持多选和搜索的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multi-Select Dropdown with Search</title>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content label {
display: block;
}
.dropdown-content label:hover {
background-color: #f1f1f1;
}
.show {display: block;}
</style>
</head>
<body>
<div class="dropdown">
<input type="text" id="myInput" onkeyup="filterFunction()" placeholder="Search.." title="Type in a name">
<div id="myDropdown" class="dropdown-content">
<label><input type="checkbox" name="vehicle" value="Bike"> Bike</label>
<label><input type="checkbox" name="vehicle" value="Car"> Car</label>
<label><input type="checkbox" name="vehicle" value="Boat"> Boat</label>
<label><input type="checkbox" name="vehicle" value="Airplane"> Airplane</label>
</div>
</div>
<script>
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("label");
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";
}
}
}
</script>
</body>
</html>
这段代码实现了一个简单的下拉框,用户可以通过输入来搜索和筛选选项。当用户在搜索框中输入时,下拉内容会根据用户的输入实时更新显示。选中的选项(复选框)会被提交,以便在表单提交时使用。
评论已关闭