我有这个代码,点击这个银块应该切换导航栏。它会触发一次,而不是第二次尝试切换导航栏。我假设这段代码有一些小错误,我找不到。
这是代码。
function toggleNav() {
var navStatus = true;
if (navStatus == true) {
document.getElementById("closenav").style.left = "-300px";
navStatus = false;
} else if (navStatus == false) {
document.getElementById("closenav").style.left = "0px";
navStatus = true;
}
}
nav {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
width: 300px;
background-color: #272727;
transition: all ease-in-out 200ms;
}
nav div {
position: fixed;
top: 40px;
left: 40px;
width: 60px;
height: 60px;
background-color: silver;
}
<nav id="closenav">
<div onclick="toggleNav()"> </div>
</nav>
答案 0 :(得分:2)
您需要在var navStatus = true
函数之外定义变量toggleNav()
,否则您的变量navStatus
值在每次点击时始终为true
,如第一次所述你的函数的行...也只是使用else
而不是else if
var navStatus = true;
function toggleNav() {
if (navStatus == true) {
document.getElementById("closenav").style.left = "-300px";
navStatus = false;
} else {
document.getElementById("closenav").style.left = "0px";
navStatus = true;
}
}
&#13;
nav {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
width: 300px;
background-color: #272727;
transition: all ease-in-out 200ms;
}
nav div {
position: fixed;
top: 40px;
left: 40px;
width: 60px;
height: 60px;
background-color: silver;
}
&#13;
<nav id="closenav">
<div onclick="toggleNav()"> </div>
</nav>
&#13;