jQuery jQuery切换带有内容的左侧边栏菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20149287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:00:22  来源:igfitidea点击:

jQuery toggle left sidebar menu with content

jqueryhtmlcss

提问by John

I have a sidebar which is open by default, i want to be able to click a menu icon and my sidebar slides in to show more of the content:

我有一个默认打开的侧边栏,我希望能够单击菜单图标,然后侧边栏滑入以显示更多内容:

 #sidebar {
  width: 210px;
  height: 100%;
  position: fixed;
  background: #2a3542;
 }

 #main-content {
  margin-left: 210px;
 }

 <div class="navbar">toggle icon in here</div>
 <div id="sidebar">sidebar content here</div>
 <section id="main-content">main page content here</section>

I want to be able to toggle the menu, but then im guessing i would have to add and remove the margin-left on to the #main-content?

我希望能够切换菜单,但是我猜我必须在#main-content 上添加和删除 margin-left ?

Any help would be great Thanks

任何帮助都会很棒谢谢

回答by The Alpha

This will work (Example)

这将起作用(示例

$('.navbar').on('click', function(){ $('#sidebar, #main-content').toggle(); });

$('.navbar').on('click', function(){ $('#sidebar, #main-content').toggle(); });

Once the element is hidden, you don't need to remove the margin or any other style of that element because, it's already hidden.

一旦元素被隐藏,您就不需要删除该元素的边距或任何其他样式,因为它已经隐藏了。

Update :Using jQuery UI's slide(Example)

更新:使用jQuery UIslide示例

$('.navbar').on('click', function(){
    $('#sidebar').toggle('slide', { direction: 'left' }, 1000);
    $('#main-content').animate({
        'margin-left' : $('#main-content').css('margin-left') == '0px' ? '210px' : '0px'
    }, 1000);
});

Update :Also you may try this (Example), using .animate()no jQuery UI

更新:你也可以试试这个(例子),使用.animate()jQuery UI

$('.navbar').on('click', function(){
    if( $('#sidebar').is(':visible') ) {
        $('#sidebar').animate({ 'width': '0px' }, 'slow', function(){
            $('#sidebar').hide();
        });
        $('#main-content').animate({ 'margin-left': '0px' }, 'slow');
    }
    else {
        $('#sidebar').show();
        $('#sidebar').animate({ 'width': '210px' }, 'slow');
        $('#main-content').animate({ 'margin-left': '210px' }, 'slow');
    }
});