使用相同按钮打开和关闭侧面菜单

目前我使用一个按钮显示侧面菜单,另一个按钮关闭它

 $('#open-menu').click(function() { $("#mySidenav").css("width" , "250px"); $("#l_m").css({"marginLeft": "250px", "position" : "absolute", "width" : "100%"}); // $(this).attr('id','close-menu'); }); $('#close-menu').click(function() { $("#mySidenav").css("width" , "0"); $("#l_m").css("marginLeft" , "0"); });  

但我希望同一个按钮打开并关闭我的菜单怎么办? 知道我使用的是Jquery 1.11.3

谢谢

(我试图添加评论的行,但是当我点击它时,没有任何反应)

将打开的样式移动到单独的css类中。 然后使用jQuery toggleClass()函数在按钮单击时切换这些类。

使用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%; } 

只需创建一个类来显示菜单,并在按钮单击时切换此类…!

 $('#open-menu').click(function() { $("#mySidenav").toggleClass('show') }); 
 #mySidenav {background: red; height: 100px; display: none;} .show {display: block !important;} 
  

这是你可以做的,我把这个“技巧”称为自定义切换:

 $(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); }); }); 

您可以使用jQuery数据属性来使用这种简单方法。

 Menu Button $('#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 */ } });