有 :focus 切换项目,包括如果您再次单击父项目

Have :focus Toggle Items Including If You Click The Parent Item Again

我有一个简单的子菜单,可以使用 :focus CSS 选择器切换到可见性。

子菜单由display: none转为display: block显示子菜单CSS:

.menu-item:focus > .submenu {
  display: block;
}

一切正常,如果我点击不同的菜单项(或页面上的其他任何地方),子菜单就会消失。

但是 CSS(我猜是 :focus)是否有可能拥有它,所以当我再次单击初始菜单项时(即第二次)它也会切换?目前这还没有发生——只有当我点击其他任何地方时才会发生(这显然是在元素失去焦点时)。

非常感谢

代码笔:https://codepen.io/emilychews/pen/RwVVmjm

body {
  display: flex;
  justify-content: center;
  margin: 0;
  height: 100vh;
  width: 100%;
}

header {
  margin-top: 2rem;
  display: flex;
  width: 50%;
  justify-content: space-evenly;
  align-items: center;
  padding: 1rem;
  background: red;
  height: 2rem;
}

.menu-item {
  position: relative;
  padding: 1rem;
  background: yellow;
  cursor: pointer;
}

/* select the focused menu-item's child elements (the submenu) */
.menu-item:focus > .submenu {
  display: block;
}

.submenu {
  display: none; /* changes to 'block' with focus */
  padding: 1rem;
  background: lightblue;
  position: absolute;
  top: 4rem;
  left: 0;
  width: 6rem;
}
<header>
  <div id="item-1" class="menu-item menu-item-1" tabindex="0">ITEM 1
    <div id="sub-item-1" class="submenu submenu-1">SUB-ITEM-1</div>
  </div>
  <div id="item-2" class="menu-item menu-item-2" tabindex="0">ITEM 2
    <div id="sub-item-2" class="submenu submenu-2">SUB-ITEM-2</div>
  </div>
</header>

我认为最好的方法是使用 JavaScript。
但是,您可以使用复选框并将包装器 div 更改为 label 仅用于 CSS 解决方案:

body {
  display: flex;
  justify-content: center;
  margin: 0;
  height: 100vh;
  width: 100%;
}

header {
  margin-top: 2rem;
  display: flex;
  width: 50%;
  justify-content: space-evenly;
  align-items: center;
  padding: 1rem;
  background: red;
  height: 2rem;
}

.menu-item {
  position: relative;
  padding: 1rem;
  background: yellow;
  cursor: pointer;
  
}

/* select the element after the checked checkbox  (the submenu) */
.dis:checked ~ .submenu {
  display: block;
}

.dis{ /*reset default checkbox style*/
  display: none
}
.submenu {
  display: none; /* changes to 'block' with focus */
  padding: 1rem;
  background: lightblue;
  position: absolute;
  top: 4rem;
  left: 0;
  width: 6rem;
}
<header>
  <label id="item-1" class="menu-item menu-item-1" tabindex="0">ITEM 1
  <input type="checkbox" class="dis">
    <div id="sub-item-1" class="submenu submenu-1">SUB-ITEM-1</div>
    
  </label>
  <label id="item-2" class="menu-item menu-item-2" tabindex="0">ITEM 2
  <input type="checkbox" class="dis">
    <div id="sub-item-2" class="submenu submenu-2">SUB-ITEM-2</div>
    
  </label>
</header>