我正在尝试使用JavaScript而不是jQuery构建一个简单的切换按钮来来回翻译元素。我尽力为新手(对于JavaScript)但无法弄清楚。主要的想法是侧面菜单应该在点击按钮时从侧面显示,并且应该在再次单击时隐藏回到相同的位置。 请帮忙。
function toggleNavBar() {
var nav = document.getElementById("sideNav"),
button = document.getElementById("checkButton"),
check = "hidden";
if (check == "hidden") {
nav.style.transform = "translate(0px)";
check = "shown";
} else if (check == "shown") {
nav.style.transform = "translate(-290px)";
check = "hidden";
}
}

body {
margin: 0 auto;
padding: 0;
}
#sideNav {
background-color: #96e6b3;
display: inline-block;
width: 20%;
position: fixed;
height: 100vh;
z-index: 2;
overflow: hidden;
-webkit-transform: translate(-290px);
/* Safari */
transform: translate(-290px);
*/
}
nav ul {
list-style-type: none;
font-family: Junction, "Times New Roman", sans-serif;
font-size: 1.9em;
margin-top: 24%;
}
nav ul li {
margin-top: 1%;
padding-top: 4.7%;
margin-left: -50px;
text-align: center;
}
nav a {
text-decoration: none;
color: #000000;
}
nav li:hover {
background-color: #34cf6d;
}

<!doctype html>
<html lang="en">
<head>
<title>Check</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<link href="font.css" rel="stylesheet" type="text/css">
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="styleCheck.css">
<style>
<!--very specific small CSS for this document--> #toggler {
text-decoration: underline;
}
#toggler:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div>
<div class="o-content">
<div class="o-container">
<div class="o-grid">
<button id="checkButton" class="c-hamburger c-hamburger--htx" onclick="toggleNavBar()">
<span>toggle menu</span>
</button>
</div>
</div>
</div>
</div>
<div id="sideNav">
<nav>
<ul>
<li><a href="indexCheck.htm">Home</a>
</li>
<li><a href="items.htm">Items</a>
</li>
<li><a href="XML.htm">XML</a>
</li>
</ul>
</nav>
</div>
<!--side Nav-->
</body>
</html>
&#13;
答案 0 :(得分:3)
您应该只声明一次check
变量:
var check = "hidden";
function toggleNavBar() {
var nav = document.getElementById("sideNav"),
button = document.getElementById("checkButton");
if (check == "hidden") {
nav.style.transform = "translate(0px)";
check = "shown";
} else if (check == "shown") {
nav.style.transform = "translate(-290px)";
check = "hidden";
}
}
一些优化(假设在文档准备就绪后完成):
var toggleNavBar = (function() {
var check = "hidden";
var nav = document.getElementById("sideNav");
var button = document.getElementById("checkButton");
return function() {
if (check == "hidden") {
nav.style.transform = "translate(0px)";
check = "shown";
} else {
nav.style.transform = "translate(-290px)";
check = "hidden";
}
}
})();