【发布时间】:2021-03-12 17:44:21
【问题描述】:
是否可以在此代码中添加一个 ID,以便在单击所需容器本身(移动导航)加上一个附加 ID(汉堡菜单-div)时不会触发。我有一个按钮来触发导航(汉堡菜单 div)。它切换一个类。所以当我点击那个特定的按钮时,这段代码应该什么都不做......这可能还是我有一个思维错误?
//Actual code and working but how to insert an additional id to avoid triggering it also on that id
document.addEventListener('mouseup', function(e) {
var container = document.getElementById('mobile-navigation');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
//Changed to this code to select multiple ids but not working
document.addEventListener('mouseup', function(e) {
var container = document.querySelectorAll('mobile-navigation, hamburger-menu-div');
if (!container.contains(e.target)) {
container.style.display = 'none';
}
});
感谢您的支持!
编辑:添加更多代码以便更好地理解:
//Toggle nav menu to show and hide
document.getElementById("hamburger-menu-div").addEventListener("click", function() {
var x = document.getElementById("mobile-navigation");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
});
//Hide it when clicked outside
var container = document.querySelectorAll('#mobile-navigation, #hamburger-menu-div');
document.addEventListener('mouseup', function(e) {
console.log(e.target);
var set = 0;
for (var i = 0; i < container.length; i++) {
if (e.target == container[i]) {
set = 1;
}
}
if (set === 0) {
container[1].style.display = 'none';
}
});
.hamburger-menu-div {
background-color: lightblue;
width: 250px;
height: 50px;
}
.mobile-navigation {
background-color: lightgreen;
width: 250px;
display: none;
position: fixed;
top: 0;
right: 0;
}
<div id="hamburger-menu-div" class="hamburger-menu-div">
BUTTON
</div>
<div id="mobile-navigation" class="mobile-navigation">
<p>- Navigationpoint 1</p>
<p>- Navigationpoint 2</p>
<p>- Navigationpoint 3</p>
<p>- Navigationpoint 4</p>
<p>- Navigationpoint 5</p>
</div>
【问题讨论】:
-
对不起,但我看不到他们放入多个 id 的任何示例。这对我没有帮助...:/
-
已编辑代码。还是不行……
标签: javascript button menu hide display