首先,我要说我有0个js知识,我试着从W3中拼凑起来
null
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
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-content {
display: none;
position: absolute;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.show {display:block;}
<li class="dropbtn">
<a onclick="myFunction()" href="#"> <i class="fa fa-user"></i> John Smith <b <i class="fa fa-caret-down"></b></a>
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
</li>
<div id="myDropdown" class="dropdown-content">
<li>
<a href="#"><i class="fa fa-fw fa-user"></i> Profile</a>
</li>
<li>
<a href="./backend/logout.backend.php"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
</li>
</div>
null
正如你所看到的,当我点击JohnSmith时,什么也不会发生,但当我点击按钮时,它就能正常工作
我也想让johnsmith工作
您可以简单地将.dropbtn
类的子元素添加到您的JS函数中,甚至不需要将该类添加到任何其他HTML元素中,如或
。
只需使用!event.target.matchs('.dropbtn,.dropbtn*')
,如下所示:
null
function myFunction(event) {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn, .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-content {
display: none;
position: absolute;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.show {display:block;}
<li class="dropbtn">
<a onclick="myFunction()" href="#"> <i class="fa fa-user"></i> John Smith <b><i class="fa fa-caret-down"></i></b></a>
<button onclick="myFunction()">Dropdown</button>
</li>
<div id="myDropdown" class="dropdown-content">
<li>
<a href="#"><i class="fa fa-fw fa-user"></i> Profile</a>
</li>
<li>
<a href="./backend/logout.backend.php"><i class="fa fa-fw fa-power-off"></i> Log Out</a>
</li>
</div>