我写了一个隐藏/显示sidenav的脚本。我的问题是我希望所有功能齐全。首先,检查sidenav是否隐藏。如果隐藏,通过单击显示sidenav并且如果sidenav可见,单击以隐藏sidenav。 我的代码:
function showSideNav () {
var sideNav = document.getElementById("slide-out");
sideNav.style.cssText = "transform: translateX(0); -webkit-transition: 0.5s;";
}
function closeSideNav () {
var sideNav = document.getElementById("slide-out");
sideNav.style.cssText = "transform: translateX(-100%); -webkit-transition: 0.5s;";
}
答案 0 :(得分:2)
如果boolean
可见或不可见,并根据其值显示或隐藏,您可以实施sidenav
变量保留信息。
var sideNav = document.getElementById("slide-out"),
sideNavVisible = true;
function toggleSideNav() {
if (sideNavVisible) {
sideNav.style.cssText = "transform: translateX(-100%); -webkit-transition: 0.5s;";
} else {
sideNav.style.cssText = "transform: translateX(0); -webkit-transition: 0.5s;";
}
sideNavVisible = !sideNavVisible;
}

* {
padding: 0;
margin: 0;
}
#slide-out {
height: 100px;
width: 100px;
background: blue;
position: absolute;
}
.container {
height: 100vh;
width: 100vw
}
.x {
right: 0;
position: fixed;
}

<div id='slide-out'></div>
<button onclick="toggleSideNav()" class='x'>Toggle sidenav</button>
<div class='container' onclick='sideNavVisible = true;toggleSideNav()'></div>
&#13;
答案 1 :(得分:1)
我认为如果将CSS放在带有类的样式表中,然后在JS中切换这些类,那么管理会更容易:
function toggleSideNav () {
var sideNav = document.getElementById("slide-out");
sideNav.classList.toggle("hidden");
sideNav.classList.toggle("visible");
}
// button for demo purposes:
document.querySelector("button").addEventListener("click", toggleSideNav);
&#13;
.visible { transform: translateX(0); -webkit-transition: 0.5s; }
.hidden { transform: translateX(-100%); -webkit-transition: 0.5s; }
&#13;
<button>Toggle</button>
<div id="slide-out" class="visible">This is my test sliding div.</div>
&#13;