Hide menu sidebar when clicking outside the bar or the button

前端 未结 5 1548
粉色の甜心
粉色の甜心 2020-12-31 22:29

I am trying to make a menu like the semantic UI but I only achieved to click the menu button and open the menu and vice versa. I use toggle class to show the sidebar but I d

相关标签:
5条回答
  • 2020-12-31 22:49

    Suppose if your sidebar width is 270px,check the mouse click coordinate.If it's greater give its style left attribute as -270px;

    function handleMousePos(event) {
          var mouseClickWidth = event.clientX;
          if(mouseClickWidth>=270){
                document.getElementById("mySidenav").style.left='-270px'
               }
    }
    
    document.addEventListener("click", handleMousePos);
    

    Here is my sample:https://codepen.io/johncy/pen/oMyzZr

    0 讨论(0)
  • 2020-12-31 22:57

    In case somebody comes here and is using Angular instead of JQuery, we got this to work with something similar to the above like this:

    public toggleSideNav() {
        this.showSideNav = !this.showSideNav;
        console.log('show side nav', this.showSideNav);
        event.stopPropagation();
    }
    
    public hideSideNav() {
        this.showSideNav = false;
        console.log('hide side nav');
    }
    

    And this in the template:

    <app-sidenav></app-sidenav>
    <div class="main-body" (click)="applicationService.hideSideNav()">
        <router-outlet></router-outlet>
    </div>
    
    0 讨论(0)
  • 2020-12-31 22:59

    Edit your js code to following

    $('#menu-button').click(function(e){
        e.stopPropagation();
        $('#hide-menu').toggleClass('show-menu');
    });
    
    $('#hide-menu').click(function(e){
        e.stopPropagation();
    });
    
    $('body,html').click(function(e){
       $('#hide-menu').removeClass('show-menu');
    });
    

    Hope this will work.

    Here is fiddle. http://jsfiddle.net/ex8ddv5q/1/

    0 讨论(0)
  • 2020-12-31 22:59
    $('body').click(function(){
         $('#hide-menu').removeClass('show-menu');
    });
    
    0 讨论(0)
  • 2020-12-31 23:02

    For a different take on it check this Fiddle

    $('#menu-button').click(function (evt) {
        evt.stopPropagation();
        $('#hide-menu').toggleClass('show-menu');
    });
    
    
    $('body,html').click(function (e) {
    
        var container = $("#hide-menu");
    
        if (!container.is(e.target) && container.has(e.target).length === 0) {
            container.removeClass('show-menu');
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题