【发布时间】:2018-12-04 11:18:24
【问题描述】:
我想包括两个按钮切换来显示/隐藏两个不同的元素,并在 div 区域之外单击时隐藏这些元素。我整天都在研究,虽然我找到了只使用一个元素的答案,但我无法让它使用两个元素。如果我在 div 外部单击时包含要隐藏的代码,则第二个元素不会显示。代码如下:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function myOtherFunction() {
document.getElementById("myResponsive").classList.toggle("show");
}
window.onclick = function(e) {
if (!(e.target.matches('.dropbtn') || e.target.matches('.mobile-button'))) {
var myDropdown =
document.getElementById("myDropdown");
var myResponsive =
document.getElementById("myResponsive");
if ((myDropdown.classList.contains('show')) ||
(myResponsive.classList.contains('show'))) {
myDropdown.classList.remove('show');
myResponsive.classList.remove('show');
}
}
}
.dropdown-content {
display: none;
float: left
}
.responsive-menu {
display: none;
float: left;
}
.show {
display: block;
}
<div>
<button class="dropbtn" onclick="myFunction()">menu1</button>
<div class="dropdown-content" id="myDropdown">
<a href="">item 1</a>
<a href="">item 2</a>
</div>
</div>
<div>
<button class="mobile-button" id="mobileMenu" onclick="myOtherFunction()">menu2</button>
<div class="responsive-menu" id="myResponsive">
<a href="">item1</a><br>
<a href="">item2</a>
</div>
</div>
非常感谢您提供一点帮助和建议。非常感谢。
【问题讨论】:
标签: javascript html css toggle hide