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

时间:2017-04-25 09:56:16

标签: javascript html css hamburger-menu

我有一个汉堡包菜单,如果点击它本身,我需要关闭它。

这是我的小提琴:

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 */
}

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

尝试this

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