选择按钮时如何关闭侧边栏?
How to close sidebar, when a button is selected?
我没用过Javascript,编程也才不到一年,做错事请不要怪我。我的问题是,单击按钮时如何关闭侧边栏?我想我应该在 Javascript 内完成,但我不知道怎么做。
这是我的 JS 代码:
function show(){
document.getElementById('sidebar').classList.toggle('active')
document.getElementById('sidebarbg').classList.toggle('active')
}
CSS 代码(这显然不是完整的 css 代码,我删除了最多):
#sidebar{
background-color: #cc2f70;
width: 310px;
height: 100%;
position: fixed;
left: -310px;
transition-duration: 0.3s;
}
#sidebarbg{
background-color: #00a6b7;
width: 300px;
height: 100%;
position: fixed;
left: -300px;
transition-delay: 0.15s;
transition-duration: 0.3s;
}
#sidebar.active{
left: 0;
}
#sidebarbg.active{
left: 0;
}
#sidebar ul{
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
position: fixed;
top: 30px;
left: 220px;
z-index: 5;
transition: 0.4s;
}
.button span{
width: 30px;
height: 5px;
background-color: white;
display: block;
margin: 5px;
}
html:
<div class="button" onclick="show()">
<span>click here</span>
<span></span>
<span></span>
</div>
<div class="logo">
<span>lo</span><br><span>go</span>
</div>
<div id="sidebar">
<div id="sidebarbg"></div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
</ul>
</div>
添加这个脚本
var lis = document.querySelectorAll("ul li");
for (var i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", show);
}
我没用过Javascript,编程也才不到一年,做错事请不要怪我。我的问题是,单击按钮时如何关闭侧边栏?我想我应该在 Javascript 内完成,但我不知道怎么做。
这是我的 JS 代码:
function show(){
document.getElementById('sidebar').classList.toggle('active')
document.getElementById('sidebarbg').classList.toggle('active')
}
CSS 代码(这显然不是完整的 css 代码,我删除了最多):
#sidebar{
background-color: #cc2f70;
width: 310px;
height: 100%;
position: fixed;
left: -310px;
transition-duration: 0.3s;
}
#sidebarbg{
background-color: #00a6b7;
width: 300px;
height: 100%;
position: fixed;
left: -300px;
transition-delay: 0.15s;
transition-duration: 0.3s;
}
#sidebar.active{
left: 0;
}
#sidebarbg.active{
left: 0;
}
#sidebar ul{
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
position: fixed;
top: 30px;
left: 220px;
z-index: 5;
transition: 0.4s;
}
.button span{
width: 30px;
height: 5px;
background-color: white;
display: block;
margin: 5px;
}
html:
<div class="button" onclick="show()">
<span>click here</span>
<span></span>
<span></span>
</div>
<div class="logo">
<span>lo</span><br><span>go</span>
</div>
<div id="sidebar">
<div id="sidebarbg"></div>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
<li><a href="#">Home</a></li>
</ul>
</div>
添加这个脚本
var lis = document.querySelectorAll("ul li");
for (var i = 0; i < lis.length; i++) {
lis[i].addEventListener("click", show);
}