导航切换功能无法正常运行

时间:2018-03-16 17:50:05

标签: javascript html css

我有这个代码,点击这个银块应该切换导航栏。它会触发一次,而不是第二次尝试切换导航栏。我假设这段代码有一些小错误,我找不到。

这是代码。

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>

1 个答案:

答案 0 :(得分:2)

您需要在var navStatus = true函数之外定义变量toggleNav(),否则您的变量navStatus值在每次点击时始终为true,如第一次所述你的函数的行...也只是使用else而不是else if

&#13;
&#13;
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;
&#13;
&#13;