【问题标题】:TWO show/hide toggles (and their hide if click outside div) issue两个显示/隐藏切换(如果单击 div 外部则隐藏)问题
【发布时间】: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


    【解决方案1】:

    您的代码无法正常工作,因为您没有正确使用 Element.matches 方法。 Element.matches 方法只接受一个与您要匹配的选择器相对应的参数 (see here)。你已经向它传递了两个参数,它只是忽略了第二个。

    要解决此问题,只需将 if 语句修改如下以正确使用 Element.matches 方法:

    if (!(e.target.matches('.dropbtn') || e.target.matches('.mobile-button')))
    

    【讨论】:

    • 感谢您的回答,这对您很有帮助。有趣的是,它最初只在我发布的嵌入式代码中起作用,而不是在我的实际网站上。我的“menu2”按钮最初是一个图像,由于某种原因,我无法使其工作,直到我将其更改为文本。
    猜你喜欢
    • 2023-03-15
    • 2014-05-05
    • 1970-01-01
    • 2022-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2013-04-18
    • 1970-01-01
    相关资源
    最近更新 更多