[英]window.addEventListener function is not working at all times
通过此代码,当用户单击按钮外部时,我必须隐藏下拉容器。 并且代码最初运行良好。 但后来,它也没有响应按钮上的 onclick 事件。 如果我点击一个按钮,有时它会关闭下拉菜单。 我已经尝试了许多 stackoverflow 问题,但没有得到答案。 这是我的代码。 希望有人能解决这个问题。
<div class="button-grp">
<button class="icon-button" type="button" onclick="menu(event, '1')"><img
src="../../Images/icons/local_library-white-24dp.svg" class="icon"><br>Learning
</button>
<button class="icon-button" type="button" onclick="menu(event, '2')"><img
src="../../Images/icons/gamepad-white-24dp.svg" class="icon"><br>Tools
</button>
</div>
<div class="sidebar-open">
<div class="main-options" id="0">
<button class="options-button" type="button">Academics</button>
<div class="dropdown-container">
<a href="#">Course Details</a>
<a href="#">Assignments</a>
</div>
<button class="options-button" type="button">Schedule</button>
<div class="dropdown-container">
<a href="#">Exams</a>
<a href="#">Classes</a>
</div>
</div>
</div>
<div id="mainmenu">
Lorem ipsum dolor sit,
</div>
我的Javascript代码如下..
//function to toggle between clicked buttons and close when double clicked on it.
function menu(evt, id) {
document.querySelectorAll(".main-options").forEach(function(div) {
if (div.id === id) {
// Toggle specified DIV
if(div.style.display === "block"){
div.style.display = "none";
document.getElementById("mainmenu").style.marginLeft = "80px";
document.body.style.backgroundColor = "#fff";
}else{
div.style.display = "block";
document.getElementById("mainmenu").style.marginLeft = "230px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
} else {
// Hide other DIVs
div.style.display = "none";
}
});
}
//function to hide the dropdown when clicked outside the button.
window.addEventListener('click', function(event){
if (!event.target.matches('.icon-button') ){
var dropdowns = document.getElementsByClassName("main-options");
var i;
for (i = 0; i < dropdowns.length; i++) {
if (dropdowns[i].style.display === "block") {
dropdowns[i].style.display ="none";
document.getElementById("mainmenu").style.marginLeft = "80px";
document.body.style.backgroundColor = "#fff";
}
}
}
});
你为什么不试试这个:
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".icon-button").forEach((button) => {
button.addEventListener('click', ()=>{
...
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.