【发布时间】:2020-10-29 09:07:37
【问题描述】:
我正在尝试制作一个下拉菜单,在单击时显示下拉内容。
我注意到当按钮包含文本时,它的行为是我想要的。但是,当它包含来自 fontawesome.com 的图标时,当我单击图标内的区域时,下拉菜单不会显示。奇怪的是,当我点击按钮内未被图标覆盖的区域时,会出现下拉菜单。
我尝试使用 material.io 中的图标更改图标,但问题仍然存在。
我不确定我的代码的哪一部分导致了问题。提前致谢。
这是我的代码:
html:
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">
<i class="far fa-envelope"></i>
</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">
Link 1
<div></div>
</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
css:
/* Dropdown Button */
.dropbtn {
/*sample code for center align text*/
background-color: #97d5ff;
color: rgb(0, 0, 0);
font-size: 1.3em;
border: 0px solid white;
border-radius: 50%;
width: 2.1em;
height: 2.1em;
cursor: pointer;
text-align: center;
}
/* Dropdown button on hover & focus */
.dropbtn:hover,
.dropbtn:focus {
background-color: #2980B9;
outline-width: 0px;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {
display: block;
}
javascript
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
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');
}
}
}
}
【问题讨论】:
标签: javascript html css drop-down-menu icons