我有一个按钮,我希望它能打开和关闭侧边导航栏。我的按钮代码是:
<button class="myBtn" id="myBtn"><i class="glyphicon glyphicon-info-sign"></i></button>
我正在尝试使用 addEventListener 并认为我可能在其中缺少 if 语句,但不能确定:
document.getElementById("myBtn").addEventListener("click", open);
function open() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
document.getElementById("myBtn").addEventListener("click", close);
function close() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft = "0";
document.body.style.backgroundColor = "white";
}
有什么建议吗?谢谢!
最佳答案
这就是我在评论中的意思......
document.getElementById("myBtn").addEventListener("click", open_close);
var menuState = 0 // close
function open_close() {
if(menuState === 0){
menuState = 1;
document.getElementById("mySidenav").style.width = "250px";
//document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
else {
menuState = 0;
document.getElementById("mySidenav").style.width = "0";
//document.getElementById("main").style.marginLeft = "0";
document.body.style.backgroundColor = "white";
}
console.log(menuState);
}
这里是 fiddle
关于javascript - 打开/关闭 sidenav 栏相同的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903036/