垂直下拉菜单关闭太快

时间:2018-02-05 09:36:05

标签: html drop-down-menu

我有一个带子菜单的简单垂直下拉菜单,但是这个让我头晕目眩。 当我点击子菜单 - 父级(下拉页面2)时,我希望加载相应的页面并打开子菜单。 当我单击子菜单中的任何项目时,我想加载相应的页面并保持子菜单打开。 当我单击子菜单父项或另一个父项(start或page1)时,我想加载相应的页面并关闭子菜单。 使用当前代码,子菜单总是立即关闭。

jsfiddle在这里:https://jsfiddle.net/bj1d17c5/

代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="screen.css"/>
</head>
<body>

<div class="sidenav">
  <a href="test.html">Start</a>
  <a href="test.html">Page1</a>
  <a href="test.html" class="dropdown-btn">Dropdown Page2</a>
  <div class="dropdown-container">
    <a href="#">Page 2.1</a>
    <a href="#">Page 2.2</a>
    <a href="#">Page 2.3</a>
  </div> 
</div>

<div class="main">
  <h2>Sidebar Dropdown</h2>
  <p>Click on the dropdown button to open the dropdown menu inside the side navigation.</p>
  <p>This sidebar is of full height (100%) and always shown.</p>
  <p>Some random text..</p>
</div>

<script>
/* Loop through all dropdown buttons to toggle between hiding and showing its dropdown content - This allows the user to have multiple dropdowns without any conflict */
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var dropdownContent = this.nextElementSibling;
    if (dropdownContent.style.display === "block") {
      dropdownContent.style.display = "none";
    } else {
      dropdownContent.style.display = "block";
    }
  });
}
</script>

</body>
</html> 

1 个答案:

答案 0 :(得分:0)

我没有得到它,但是,因为你正在使用href来测试它&#34; test.html&#34 ;?试试这个: <a href="#" class="dropdown-btn">Dropdown Page2</a>