我正在尝试创建一个css侧面菜单但是当我关闭菜单时,将div容器宽度设置为0,链接仍然可见。
这是jsfiddle - https://jsfiddle.net/atLvp6k7/
有趣的是,当我将菜单设置在屏幕右侧时,我没有遇到同样的问题。我是否需要为项目添加保证金属性?
<div id="side-menu" class="side-nav">
<img id="close-side" src="https://floraisabelle.com/assets/images/hamburger-menu.png?v=aa3f825eb7" alt="">
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
</div>
var isOpen = false;
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("side-menu").style.width = "0px";
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = false;
} else {
document.getElementById("side-menu").style.width = "250px";
document.getElementById("close-side").style.marginLeft = "181px";
isOpen = true;
}
})
.side-nav {
transition: .5s;
height: 100%;
width:0;
background-color: rgba(120, 120, 120, 0.1);
position: fixed;
top: 0;
left: 0;
z-index: 1;
}
#close-side {
margin-left: 0;
margin-top: 5px;
transition: linear .5s;
position: fixed;
}
答案 0 :(得分:1)
<强> CSS 强>
.side-hidden a {
display: none;
}
<强> HTML 强>
<div id="side-menu" class="side-nav side-hidden">
<强> SCRIPT 强>
var isOpen = false;
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("side-menu").classList.add('side-hidden');
document.getElementById("side-menu").style.width = "0px";
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = false;
} else {
document.getElementById("side-menu").classList.remove('side-hidden');
document.getElementById("side-menu").style.width = "250px";
document.getElementById("close-side").style.marginLeft = "181px";
isOpen = true;
}
})
我也更新了你的小提琴 https://jsfiddle.net/atLvp6k7/1/
不需要isOpen Variable
if(document.getElementById("side-menu").classList.contains('side-hidden')){
alert('isClosed');
}else{
alert('isOpen');
}
答案 1 :(得分:1)
您可以更改侧边栏的边距而不是宽度....
这是怎么做的 -
document.getElementById('close-side').addEventListener("click", function(){
if (isOpen) {
document.getElementById("close-side").style.marginLeft = "-100px";
isOpen = false;
} else {
document.getElementById("close-side").style.marginLeft = "0px";
isOpen = true;
}
})
并将按钮(关闭侧)放在侧边栏div
之外<img id="close-side" src="https://floraisabelle.com/assets/images/hamburger-menu.png?v=aa3f825eb7" alt="">
<div id="side-menu" class="side-nav">
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
<a class="" href="#">Hi</a>
</div>
现在将以下css应用于过渡效果 -
.side-nav
{
transition: all 0.5s ease;
}