【问题标题】:Close dropdown when other dropdown is opened打开其他下拉菜单时关闭下拉菜单
【发布时间】:2017-10-20 18:05:27
【问题描述】:

这是我的代码:https://jsfiddle.net/qesr0ybf/

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

/* When the user clicks on the button, 
toggle between hiding and showing the dropdown content */
function myFunction2() {
  document.getElementById("myDropdown2").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

当一个下拉菜单打开时,另一个可以同时打开。我试图让另一个关闭,一次只打开一个。怎么办?

【问题讨论】:

    标签: javascript dropdown


    【解决方案1】:

    将你的函数更新为:

    function myFunction() {
        var d2 = document.getElementById("myDropdown2").classList;
        if(d2.contains("show")) d2.toggle("show");
        document.getElementById("myDropdown").classList.toggle("show");
    }
    

    和其他功能类似。

    即检查另一个下拉列表是否包含 show 类,然后将其删除。

    更好的方法是跟踪上次打开的下拉菜单并在打开另一个下拉菜单之前将其关闭,但由于您只有两个下拉菜单,所以应该这样做。

    现场演示here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多