jQuery用内容切换左侧边栏菜单

Joh*_*ohn 2 html css jquery html5 css3

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

 #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>
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会很棒谢谢

The*_*pha 5

这将工作(例子)

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

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

更新:使用jQuery UI's slide(示例)

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

更新:您也可以尝试这个(示例),使用.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');
    }
});
Run Code Online (Sandbox Code Playgroud)