响应式导航栏的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%;
}

这样尝试:

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.thoggle((方法添加/删除checkedNavbar

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

最新更新