边栏菜单在点击时不会折叠

时间:2019-01-17 17:11:28

标签: javascript

当用户单击左侧的垂直黑色边框时,将显示侧边栏菜单,但是当我单击关闭按钮时,它不会折叠。我希望它使用与javascript或jquery相同的动画关闭。

<div id="mySidenav" class="sidenav" onclick="openNav()" style="cursor: pointer;">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<h2>Animated Sidenav</h2>

<script>
function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}
</script>

演示https://jsfiddle.net/1n6bajmh/

2 个答案:

答案 0 :(得分:3)

它不起作用,因为您在嵌套元素上注册了两个onclick事件处理程序。

当您单击内部一个元素以关闭菜单时,确实会正确调用closeNav函数,但是click事件会在DOM树中向上传播,到达ID为“ mySidenav”的父ID。

现在,div也具有注册的onclick处理程序,该处理程序也会被触发,因此您的openNav函数也会被调用。

您需要防止事件向上传播并到达div,因此可以使用event.stopPropagation()。

检查一下:

function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav(event) {
  event.stopPropagation();
  document.getElementById("mySidenav").style.width = "0";
}
body {
  font-family: "Lato", sans-serif;
}

.sidenav {
  height: 100%;
  width: 15px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidenav a:hover {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

@media screen and (max-height: 450px) {
  .sidenav {
    padding-top: 15px;
  }
  .sidenav a {
    font-size: 18px;
  }
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<div id="mySidenav" class="sidenav" onclick="openNav()" style="cursor: pointer;">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav(event)">&times;</a>
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<h2>Animated Sidenav</h2>

我建议您在此处阅读更多有关事件冒泡的信息: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

答案 1 :(得分:-1)

如果您在openNav中更改代码以同时处理打开和关闭操作,则会解决此问题。

function openNav() {
  var w = document.getElementById("mySidenav").style.width;
  if(w === "250px"){
    document.getElementById("mySidenav").style.width = '2px';
  }else {
   document.getElementById("mySidenav").style.width = '250px';
  }
}