【问题标题】:jQuery toggle left sidebar menu with contentjQuery 用内容切换左侧边栏菜单
【发布时间】:2013-11-22 16:04:20
【问题描述】:

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

 #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>

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

任何帮助都会很棒 谢谢

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    这会起作用 (Example)

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

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

    更新:使用jQuery UIslide (Example)

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

    更新:你也可以试试这个(Example),使用.animate() no 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');
        }
    });
    

    【讨论】:

    • 我只需要隐藏侧边栏,所以我只需切换侧边栏,这样我就可以看到更多的主要内容区域。所以侧边栏默认是打开的,我点击图标隐藏它,主要内容区域在全视图中切换。我再次单击该图标,侧边栏将主要内容区域推到上方,以便它们都在视图中?