javascript - 使用复选框的响应式导航栏的 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>
- 复选框
onclick
属性更改为EnableDisableNavbar()
- JavaScript classList.toggle()方法可用于在
checkedNavbar
每次单击复选框时添加/删除类。
在复选框的父元素样式发生变化的情况下,可能需要像这样切换类的方法,因为在 CSS 中无法使用input:checked
.
推荐阅读
- node.js - 服务器可以(或应该)向客户端发送预告片(尾标)吗?
- c++ - 错误 c2953:制作双链接列表时出错
- android - Fastlane & Flutter - Google Api 错误:无效请求 - 未配置访问。谷歌播放
- c++ - 未初始化的值使用,使用 sprintf 或 strcat 时出错
- python - 从 .txt(文本)文件解析表
- java - 使用 JDK>=9 远程调试 yajsw 包装的应用程序
- nativescript-angular - Nativescript-angular tns 运行失败并出现错误错误:无法解析 ApplicationModule 的所有参数
- javascript - React 中的 Axios 请求问题
- amazon-redshift - 我们是否可以使用 debezium 在目标数据库(redshift)中创建每日快照作为行
- java - 如何将多个枚举数据写入单个 pojo 并将其作为列表返回