单击任意位置以关闭侧面导航栏 javascript

tx-*_*911 5 html javascript css twitter-bootstrap

我在引导程序中使用以下代码段在导航栏中显示侧边栏。

我可以通过单击侧边栏中的 X 按钮来关闭导航栏。如何更改我的 closeNav javascript 以便能够通过单击页面上的任意位置以及仅使用 javascript 的关闭按钮来关闭侧边栏?

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

  /* Set the width of the side navigation to 0 and the left margin of the page content to 0 */
  function closeNav() {
      document.getElementById("mySidenav").style.width = "0";
      document.getElementById("main").style.marginLeft = "0";
      }
  
Run Code Online (Sandbox Code Playgroud)
/* The side navigation menu */
.sidenav {
    height: 100%; /* 100% Full-height */
    width: 0; /* 0 width - change this with JavaScript */
    position: fixed; /* Stay in place */
    z-index: 1; /* Stay on top */
    top: 0;
    left: 0;
    background-color: #111; /* Black*/
    overflow-x: hidden; /* Disable horizontal scroll */
    padding-top: 60px; /* Place content 60px from the top */
    transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}

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

/* When you mouse over the navigation links, change their color */
.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

/* Position and style the close button (top right corner) */
.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
    transition: margin-left .5s;
    padding: 20px;
}

/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
@media screen and (max-height: 450px) {
    .sidenav {padding-top: 15px;}
    .sidenav a {font-size: 18px;}
}
Run Code Online (Sandbox Code Playgroud)
<div id="mySidenav" class="sidenav">
  <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>

<!-- Use any element to open the sidenav -->
<span onclick="openNav()">Siderbar Button click here</span>

<div id="main">
Body content is here</div>
Run Code Online (Sandbox Code Playgroud)

Nic*_*rdo 5

先说第一件事。我建议您根本不要在 HTML 中使用 onclick 属性,这就是创建事件侦听器的原因

document.querySelector('span#open_menu').addEventListener('click', openNav)

document.querySelector('.closebtn').addEventListener('click', closeNav)
Run Code Online (Sandbox Code Playgroud)

其次,只需以相同的方式向#main div 添加另一个事件侦听器,请记住,您可以使用不同的元素触发相同的事件,完全没有问题

document.querySelector('#main').addEventListener('click', closeNav)
Run Code Online (Sandbox Code Playgroud)

记住在 HTML 中始终使用事件侦听器,不要使用 JS!