我有此代码,单击此银色块应可切换导航栏。它只会触发一次,并且不会第二次尝试切换回导航栏。我假设这段代码有一些小错误,但我找不到。这是代码。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> 最佳答案 您将需要在var navStatus = true函数之外定义变量toggleNav(),否则每次单击时变量navStatus的值将始终为true,如函数第一行所述...也可以使用而不是elsevar navStatus = true;function toggleNav() { if (navStatus == true) { document.getElementById("closenav").style.left = "-300px"; navStatus = false; } else { 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> 10-05 23:02