嘿我正在尝试建立一个带有导航栏的网站,该导航栏在我设法完成的页面上滑动,但打开菜单的按钮与关闭它的按钮不同。我想要它打开和关闭它所以我不需要有一个以上的按钮。我建立它的例子来自w3学校:https://www.w3schools.com/howto/howto_js_sidenav.asp
我在考虑使用else if语句,但不确定我会怎么做... 一切都很简短:我想更改openNav函数,因此当没有点击按钮时,它与openNav具有相同的效果,而当点击按钮时,它与closeNav相同。 (对不起,如果我不能解释清楚的话) 感谢所有答案:)
到目前为止我的代码:
/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "150px";
}
/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
}
<div id=main>
<div id= button>
<span onclick="openNav()"><div id=bar></div>
<div id=bar></div>
<div id=bar></div></span></div>
</div>
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
答案 0 :(得分:1)
嗯,我想你会选择这样的东西:
function toggleNav() {
var d = document;
var navWidth = d.getElementById("mySidenav").style.width;
if (navWidth === "0" || navWidth === "") {
d.getElementById("mySidenav").style.width = "250px";
d.getElementById("main").style.marginLeft = "150px";
} else {
d.getElementById("mySidenav").style.width = "0";
d.getElementById("main").style.marginLeft = "0";
}
}
答案 1 :(得分:0)
我要做的是创建一个具有布尔值的不同函数,以查看它当前是打开还是关闭。
在该功能中,您可以在关闭时打开,或者在打开时关闭;
我必须警告你,没有太多时间在我的手机上这么快打字:
var open = false;
function decide(){
if(open == true){
closeNav();
}else{
openNav();
}
}
/* Set the width of the side navigation to 250px and the left margin of the page content to 250px and add a black background color to body */
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "150px";
open = true;
}
/* Set the width of the side navigation to 0 and the left margin of the page content to 0, and the background color of body to white */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
open = false;
}
如果你使用它,你只需要一个按钮。触发decision()的按钮,然后调用其中一个函数。
答案 2 :(得分:0)
声明一个全局变量并创建一个新函数
示例:
var is_nav_open = false;
function toggleNav() {
if(is_nav_open == false) {
is_nav_open = true;
openNav();
} else {
is_nav_open = false;
closeNav();
}
}
然后改变
<span onclick="openNav()"><div id=bar></div>
和
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
调用我们的新函数toggleNav()
像
<span onclick="togglenNav()"><div id=bar></div>
和
<a href="javascript:void(0)" class="closebtn" onclick="togglenNav()">×</a>