单击其他地方时关闭汉堡菜单

Close Hamburger Menu when clicked elsewhere

我有一个汉堡包菜单,如果单击它本身以外的任何地方,我需要将其关闭。

这是我的 fiddle :

Fiddle

我的代码如下所示:

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

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: medium;
    /* color: #818181; */
    display: block;
    transition: 0.3s;
    border-bottom:1px solid black;
}

.sidenav a:hover, .offcanvas a:focus{
    color: #f1f1f1;
}

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

/* #main {
    transition: margin-left .5s;
    padding: 16px;
} */

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}
.menu{z-index:1000000; font-weight:bold; font-size:0.8em; width:100%; background:#f1f1f1;  position:absolute; text-align:center; font-size:12px;}
.leftFloat{
    float:left;
}
::-webkit-scrollbar {
    width: 0px !important;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}

试试这个:

window.onclick = function(event) {
  if ($('#mySidenav').width() == 250) {
    $('#mySidenav').width(0);
  }
}

尝试this

$(document).click(function(event) {
  if (!$(event.target).closest('#mySidenav, #checkOpen').length) {
    if ($('#mySidenav').is(":visible")) {
      document.getElementById("mySidenav").style.width = "0px";
    }
  }
})