简体   繁体   English

单击正文以关闭侧面菜单

[英]Close Sidemenu by Clicking in Body

I would like the menu to act like the sidemenu on Medium , when the sidemenu is open and the user clicks outside #sidebar-wrapper , the sidemenu closes. 我希望菜单的行为类似于Medium上的sidemenu,当sidemenu打开并且用户在#sidebar-wrapper之外单击时,sidemenu关闭。 Right now I have to click the toggle X to close the menu. 现在,我必须单击切换开关X以关闭菜单。

html html

<a id="menu-toggle" href="#" class="toggle more navbar-brand">logo</a>
<div id="sidebar-wrapper">
      <a id="menu-close" href="#" class="toggle">X</a>
</div

some css 一些CSS

#sidebar-wrapper {
    margin-left: -230px;
    left: 0;
    top: -20px;
    width: 230px;
    background: #f7f7f7;
    position: fixed;
    height: 120%;
    overflow-y: auto;
    z-index: 1000;
    -webkit-transition: all 0.4s ease 0s;
    -moz-transition: all 0.4s ease 0s;
    -ms-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

#sidebar-wrapper.active {
    left: 230px;
    width: 230px;
    border-right: 1px solid #ccc;
    -webkit-transition: all 0.4s ease 0s;
    -moz-transition: all 0.4s ease 0s;
    -ms-transition: all 0.4s ease 0s;
    -o-transition: all 0.4s ease 0s;
    transition: all 0.4s ease 0s;
}

js js

<script> 
   // menu close function
   $("#menu-close").click(function(e) {
       e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
   });
</script>

<script>  
   // menu open function
   $("#menu-toggle").click(function(e) {
       e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
   });
</script>

Try this 尝试这个

$("#menu-close").click(function(e) {
   e.stopPropagation();
   $("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function(e) {
   e.stopPropagation();
   $("#sidebar-wrapper").toggleClass("active");
});
$(document).click(function(){
   if($("#sidebar-wrapper").hasClass('active')){
      $("#sidebar-wrapper").removeClass("active");
   }
});

DEMO 演示

use stopPropagation it prevent from event bubbling 使用stopPropagation可以防止事件冒泡

$("#menu-close").click(function(e) {
       e.stopPropagation();
       $("#sidebar-wrapper").toggleClass("active");
 });

  $(document).click(function(e) {
           $("#sidebar-wrapper").toggleClass("active");
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM