我设法让sidenav打开但无法让它关闭。我已经读过使用条件法是要走的路,但是这里没有做它应该做的事情。
这是我的代码:
var sidenav = document.getElementById("sidenav");
var page = document.getElementById("page");
function togNav() {
if (sidenav.style.width = '0px') {
sidenav.style.width = "200px";
page.style.marginLeft = "200px";
} else {
sidenav.style.width = "0px";
page.style.marginLeft = "0px";
}
}
body {
margin: 0;
padding: 0;
}
.openbtn {
background: none;
border: none;
outline: none;
cursor: pointer;
}
#bar {
width: 25px;
height: 3px;
margin: 6px;
background: #999;
border-radius: 5px;
}
.sidenav {
height: 100%;
width: 0px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #eee;
overflow-x: hidden;
transition: 0.5s;
}
.sidenav ul {
margin: 0;
padding: 0;
}
.sidenav li {
list-style-type: none;
}
.sidenav a {
color: #555;
display: block;
padding: 15px 0px 15px 75px;
text-decoration: none;
border-bottom: 0.1px #ddd solid;
font-weight: 300;
font-family: helvetica neue;
}
.sidenav a:hover {
background: #ddd;
}
#page {
margin-left: 0px;
transition: 0.5s;
}
<div class="sidenav" id="sidenav">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
</div>
<div id="page">
<button id="openbtn" class="openbtn" onclick="togNav()">
<div id="bar"></div>
<div id="bar"></div>
<div id="bar"></div>
</button>
</div>
答案 0 :(得分:0)
如果情况有误。您使用的是=
(作业),而是使用==
进行比较
var sidenav = document.getElementById("sidenav");
var page = document.getElementById("page");
function togNav() {
if (sidenav.style.width == '0px') { // here
sidenav.style.width = "200px";
page.style.marginLeft = "200px";
} else {
sidenav.style.width = "0px";
page.style.marginLeft = "0px";
}
}
body {
margin: 0;
padding: 0;
}
.openbtn {
background: none;
border: none;
outline: none;
cursor: pointer;
}
#bar {
width: 25px;
height: 3px;
margin: 6px;
background: #999;
border-radius: 5px;
}
.sidenav {
height: 100%;
width: 0px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #eee;
overflow-x: hidden;
transition: 0.5s;
}
.sidenav ul {
margin: 0;
padding: 0;
}
.sidenav li {
list-style-type: none;
}
.sidenav a {
color: #555;
display: block;
padding: 15px 0px 15px 75px;
text-decoration: none;
border-bottom: 0.1px #ddd solid;
font-weight: 300;
font-family: helvetica neue;
}
.sidenav a:hover {
background: #ddd;
}
#page {
margin-left: 0px;
transition: 0.5s;
}
<div class="sidenav" id="sidenav">
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
<li><a href="#">Link 4</a></li>
<li><a href="#">Link 5</a></li>
</ul>
</div>
<div id="page">
<button id="openbtn" class="openbtn" onclick="togNav()">
<div id="bar"></div>
<div id="bar"></div>
<div id="bar"></div>
</button>
</div>