导航栏下拉问题

时间:2017-11-10 13:07:52

标签: html css checkbox drop-down-menu

我正在尝试使用CSS制作导航菜单(因为我不知道JavaScript),它在点击顶级链接时显示子菜单,然后在顶级链接时消失再次点击。我使用了复选框和标签来实现这一目标。

效果很好,但是有一个小问题。如果您点击"菜单2"下拉列表出现,这很好。但如果你徘徊在"菜单2"再次返回,子菜单重新出现,没有点击"菜单2"第一

如何将其悬停在菜单项2之后再返回,"菜单2"必须再次单击以显示子菜单?

here is a codepen I made to demonstrate



nav {
  width: 200px;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav>ul>li {
  float: left;
}

nav a {
  height: 40px;
  width: 100px;
  display: block;
  background: lightblue;
  text-decoration: none;
  line-height: 40px;
  text-align: center;
  color: black;
}

nav>ul>li>a:hover {
  background: skyblue;
}

nav ul ul a {
  height: 20px;
  background: lightgreen;
  line-height: 20px;
}

nav ul ul a:hover {
  background: limegreen;
}

nav label {
  display: block;
}

nav input {
  display: none;
}

nav ul ul {
  display: none;
}

nav li:hover input:checked+ul {
  display: block;
}

<nav>
  <ul>
    <li><a href="#">Menu 1</a></li>
    <li><a href="#"><label for="submenucb">Menu 2&#9662;</label></a>
      <input id="submenucb" type="checkbox">
      <ul>
        <li><a href="#">Sub Menu 1</a></li>
        <li><a href="#">Sub Menu 1</a></li>
        <li><a href="#">Sub Menu 1</a></li>
      </ul>
    </li>
  </ul>
</nav>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以从选择器中删除:hover。只有在单击项目时才会显示下拉列表。

 input:checked+ul {
      display: block;
    }

&#13;
&#13;
nav {
  width: 200px;
}

nav ul {
  list-style: none;
  padding: 0;
}

nav>ul>li {
  float: left;
}


/* top level links */

nav a {
  height: 40px;
  width: 100px;
  display: block;
  background: lightblue;
  text-decoration: none;
  line-height: 40px;
  text-align: center;
  color: black;
}

nav>ul>li>a:hover {
  background: skyblue;
}


/* sub level links */

nav ul ul a {
  height: 20px;
  background: lightgreen;
  line-height: 20px;
}

nav ul ul a:hover {
  background: limegreen;
}


/* dropdown behaviour */

nav label {
  display: block;
}

nav input {
  display: none;
}

nav ul ul {
  display: none;
}

input:checked+ul {
  display: block;
}
&#13;
<nav>
  <ul>
    <li><a href="#">Menu 1</a></li>
    <li><a href="#"><label for="submenucb">Menu 2&#9662;</label></a>
      <input id="submenucb" type="checkbox">
      <ul>
        <li><a href="#">Sub Menu 1</a></li>
        <li><a href="#">Sub Menu 1</a></li>
        <li><a href="#">Sub Menu 1</a></li>
      </ul>
    </li>
  </ul>
</nav>
&#13;
&#13;
&#13;