我写了这段代码,但它隐藏了选项,而不是整个面板
option { display: none; }
我想隐藏该面板,因为我想创建自己的自定义面板
您可以尝试以下代码从头开始创建自定义选择下拉面板:
document.addEventListener("DOMContentLoaded", function() {
var dropdownButton = document.getElementById("dropdown-button");
var dropdownContent = document.querySelector(".dropdown-content");
dropdownButton.addEventListener("click", function(event) {
// HERE!!! Comment the line below if you want to make the dropdown selection pannel invisible to the user
dropdownContent.classList.toggle("show");
});
document.addEventListener("click", function(event) {
if (!event.target.closest(".custom-dropdown")) {
dropdownContent.classList.remove("show");
}
});
});
.custom-dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
padding: 8px 0;
z-index: 1;
}
.dropdown-content a {
display: block;
padding: 8px 16px;
text-decoration: none;
color: #333;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown-content.show {
display: block;
}
<div class="custom-dropdown">
<button id="dropdown-button">Select an option</button>
<div class="dropdown-content">
<a href="#">Option 1</a>
<a href="#">Option 2</a>
<a href="#">Option 3</a>
</div>
</div>
我认为使用上面的代码,不需要使下拉选择不可见。然而,在代码片段中,有一条注释引导您到 JS 中的行,您应该注释以使这个新的下拉列表不可见。
或者,您可能想看看 Bootstrap (https://getbootstrap.com/docs/4.0/components/dropdowns/) 等库,看看它们提供的可自定义下拉菜单是否适合您的需求。
希望这有帮助!愿代码与您同在...