我正在做一个下拉菜单,我希望它在我点击下拉按钮时打开,我看了一个 w3schools 教程,为什么它不起作用?
我复制了所有的教程,但我不知道为什么它不起作用
HTML(我只更改了下拉 ID 和函数名称)
CSS(我只改变了尺寸和颜色)
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropdown {
float: right;
margin-right: 115px;
overflow: hidden;
}
.dropdown .dropbtn {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: #ff0000;
font-family: inherit;
margin: 0;
}
.dropbtn:hover {
cursor: pointer;
}
.dropdown:hover {
background-color: #ff7b7b;
text-decoration: none;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #ff0000 !important;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
opacity: 0;
-webkit-transition: opacity .3s ease-in;
-moz-transition: opacity .3s ease-in;
-o-transition: opacity .3s ease-in;
transition: opacity .3 ease-in;
}
.dropdown-content a {
float: none;
color: black;
padding: 14px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ff7b7b;
}
.show {
display: block;
z-index: 11;
}
<div class="dropdown">
<button class="dropbtn" onclick="myFunction()"><li class="fa fa-bars fa-2x"></li></button>
<div class="dropdown-content" id="myDropdown">
<a href="signup.php" style="color: white;">Signup</a>
<a href="#" style="color: white;">Info</a>
<a href="#" style="color: white;">Last news</a>
</div>
</div>
如果我点击 dropdown-btn 它不起作用
考虑了一个详细信息/摘要解决方案。代码少得多,并且已经内置了下拉功能:
<details><summary>Items</summary>
<div onclick="">Item 1</div>
<div onclick="">Item 2</div>
<div onclick="">Item 3</div>
<div onclick="">Item 4</div>
</details>
注意:除 Edge 外,所有浏览器均支持。
我是一名优秀的程序员,十分优秀!