下拉列表选择框(Dropdown List)是一种常见的用户界面元素,允许用户从预定义的选项列表中选择一个或多个选项。在HTML中,通常使用<select>
元素来实现下拉列表。然而,使用JavaScript和CSS,我们可以创建一个自定义的下拉列表选择框,以提供更好的样式和交互体验。
以下是一个简单的自定义下拉列表选择框的示例代码:
<!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>
.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 a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #f1f1f1;
}
.dropdown:hover .dropdown-content {
display: block;
}
</style>
</head>
<body>
<div class="dropdown">
<button>Dropdown</button>
<div class="dropdown-content">
<a href="#">Option 1</a>
<a href="#">Option 2</a>
<a href="#">Option 3</a>
</div>
</div>
<script>
document.querySelector('.dropdown button').addEventListener('click', function() {
document.querySelector('.dropdown-content').classList.toggle('show');
});
window.onclick = function(event) {
if (!event.target.matches('.dropdown button')) {
var dropdowns = document.getElementsByClassName('dropdown-content');
for (var i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
</body>
</html>
.dropdown-content
样式没有设置display: none;
。<a>
标签有正确的href
属性。touchstart
事件替代click
事件以提高移动设备的响应性。通过以上方法,你可以创建一个功能齐全且样式自定义的下拉列表选择框。
领取专属 10元无门槛券
手把手带您无忧上云