我希望不仅可以通过单击x来关闭我的下拉菜单,还可以通过单击其外部来关闭它。我的js代码似乎无效。 Javascript是从我留在某处的模板复制而来的,但我实际上无法对其进行修复以使其正常工作。
window.onclick = function closeMenu() {
if(document.getElementById("dropdown-content").style.left != "-300px") {
var dropdown = document.getElementById("dropdown-content");
var i;
for(i = 0; i < dropdown.length; i++) {
var openDropdown = dropdown[i];
if(openDropdown.style.left != ('-300px')) {
openDropdown.style.left = ('-300px');
}
}
}
}
.dropdown-content {
position: fixed;
background-color: rgb(255, 255, 255);
width: 300px;
height: 100%;
/*box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);*/
z-index: 600;
transition: 0.3s;
}
#dropdown-content {
left: -300px;
z-index: 600;
}
<div class="dropdown-container">
<div class="dropdown-content" id="dropdown-content">
<div class="menubutton" onclick="menu(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<div class="menulist">
<a href="#">Angebot des Tages</a>
<a href="#">Alle Angebote</a>
<a href="#">Technik</a>
<a href="#">Hardware</a>
<a href="#">Mode</a>
<a href="#">Automobil</a>
</div>
</div>
</div>
答案 0 :(得分:1)
const x = document.querySelector('.x');
const ul = document.querySelector('ul');
x.addEventListener('click', () => {
ul.classList.toggle('show');
});
document.addEventListener('click', ({
target
}) => {
if (target.matches('.x') === false) {
ul.classList.remove('show');
}
});
ul {
display: none;
}
ul.show {
display: block;
}
<div class="x">X</div>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
在这里,我们跟踪X
并仅使用toggle()
,对于其他任何点击,我们都确保它不是X
,而只是remove()
我们的表演班。
答案 1 :(得分:0)
如果您仅使用原始javascript,则可以将eventListener
添加到侦听document
事件的click
对象中,并检查下拉菜单的某些情况以检查其是否打开,如果是,则将其关闭;如果不是,则什么也不做。
类似的东西:
document.addEventListener('click', () => {
const dropdown = ... // grab dropdown element
if (isOpened(dropdown)) closeDropdown()
})
编辑:另外,您还应该检查单击是否发生在下拉菜单之外,因为单击该按钮也会触发它。为此,您可以使用Node API。
保留为:
document.addEventListener('click', (e) => {
const dropdown = ... // grab dropdown element
if (dropdown.contains(e.target)) return; // if the clicked element is inside the dropdown or it's the dropdown itself, do nothing
if (isOpened(dropdown)) closeDropdown()
})