首页 > 解决方案 > 使用复选框的响应式导航栏的 JavaScript 是否选中

问题描述

我需要一个Javascript,同时在选中复选框时添加类checkedNavbar,并在未选中时将其删除。

      <div class="hamburger">
        <input type="checkbox" id="check" onclick="EnableDisableNavbar"/>
        <label for="check" class="checkButton">
          <i class="fas fa-bars" style="font-size: 35px"></i>
        </label>
      </div>

我想在选中时添加一个类,并在未选中时将其删除。这是我的CSS:

    ul{
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100vh;
        z-index: 0;
        right: 0;
        background-color: #e54136;
    }
    ul li{
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        margin: 15px 0;
    }
    ul li a{
        font-size: 30px;
    }
    .checkedNavbar{
        right: 100%;
    }

标签: javascripthtmlcssnavbar

解决方案


试试这样:

function EnableDisableNavbar() {
  document.querySelector(".hamburger").classList.toggle("checkedNavbar");
}
ul {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  z-index: 0;
  right: 0;
  background-color: #e54136;
}

ul li {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  margin: 15px 0;
}

ul li a {
  font-size: 30px;
}

.checkedNavbar {
  right: 100%;
}

/* Below added for demo only */
.hamburger {
   background-color: yellow;
}

.checkedNavbar {
   background-color: purple;
}
<div class="hamburger">
  <input type="checkbox" id="check" onclick="EnableDisableNavbar()" />
  <label for="check" class="checkButton">
    <i class="fas fa-bars" style="font-size: 35px"></i>
  </label>
</div>

  1. 复选框onclick属性更改为EnableDisableNavbar()
  2. JavaScript classList.toggle()方法可用于在checkedNavbar每次单击复选框时添加/删除类。

在复选框的父元素样式发生变化的情况下,可能需要像这样切换类的方法,因为在 CSS 中无法使用input:checked.


推荐阅读