Open and close side menu with same button

前端 未结 4 814
耶瑟儿~
耶瑟儿~ 2021-01-24 22:24

Currently I use one button to display a side menu and another to close it



        
相关标签:
4条回答
  • 2021-01-24 22:58

    Move the open styles into separate css classes. Then toggle these classes on button click using the jQuery toggleClass() function.

    Javascript:

    $('#toggle-menu').click(function() {
      $("#mySidenav").toggleClass("open");
      $("#l_m").toggleClass("open");
    });
    

    CSS:

    #mySidenav {
      width: 0;
    }
    
    #mySidenav.open {
      width: 250px;
    }
    
    #l_m {
      margin-left: 0;
    }
    
    #l_m.open {
      position: absolute;
      margin-left: 250px;
      width: 100%;
    }
    
    0 讨论(0)
  • 2021-01-24 23:02

    You can use this simple approach using jQuery data attribute.

    <a id="menu" data-stat="close">Menu Button</a>
    
    $('#menu').on('click', function(){
        if($(this).data('stat') == "close"){
            $(this).data('stat', 'open');
    
            /* open Menu code */
    
        }else if($(this).data('stat') == "open"){
            $(this).data('stat', 'close');
    
            /* close Menu code */
    
        }
    });
    
    0 讨论(0)
  • 2021-01-24 23:10

    Here's what you can do, I call this "trick" a custom toggle :

    $(document).ready(function(){
      $(/*selector for the button*/)
        .click(function(){
          const $this = $(this);
          let prop = $this.prop("opened");
    
          if(prop === undefined){
            $this.prop("opened", false);
            prop = $this.prop("opened");
          }
    
          if(prop === false){
            /*handle opening here*/
          }
    
          if(prop === true){
            /*handle closing here*/
          }
    
          $this.prop("opened", !prop);
        });
    });
    
    0 讨论(0)
  • 2021-01-24 23:13

    Just make a class to show the menu and toggle this class on button click...!

    $('#open-menu').click(function() {
      $("#mySidenav").toggleClass('show')
    });
    #mySidenav {background: red; height: 100px; display: none;}
    .show {display: block !important;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div id="mySidenav"></div>
    <button id="open-menu">Menu</button>

    0 讨论(0)
提交回复
热议问题