2015-02-23 152 views
2

我正在使用此Bootstrap示例工作的网站,在侧边栏导航中使用简单的幻灯片。关闭侧边栏点击外部

http://ironsummitmedia.github.io/startbootstrap-simple-sidebar/#

据稍加修改,所以我对菜单按钮打开:

// Opens the sidebar menu 
$("#menu-toggle").click(function (e) { 
    e.preventDefault(); 
     $("#sidebar-wrapper").toggleClass("active"); 
}); 

而且对于菜单按钮关闭:

// Closes the sidebar menu 
    $("#menu-close").click(function (e) { 
     e.preventDefault(); 
     $("#sidebar-wrapper").toggleClass("active"); 
    });  

我想要添加功能,所以如果我点击边栏以外的任何地方,它将关闭。到目前为止,我有这样的:

// Close the menu on click outside of the container 
$(document).click(function (e) { 

      var container = $("#sidebar-wrapper"); 

      if (!container.is(e.target) // if the target of the click isn't the container... 
       && container.has(e.target).length === 0 // ... nor a descendant of the container 
       && event.target.id !== "menu-toggle") // for the functionality of main toggle button 
      { 
       container.removeClass("active"); 
      } 
    }); 

但它似乎删除这种“主动”类。

此致敬礼。

回答

0

试试这个

$(document).click(function (e) 
{ 
    var container = $("#wrapper"); 

    if (!container.is(e.target) && container.has(e.target).length === 0 && event.target.id!=="menu-toggle") 
    { 
     container.addClass("toggled"); 
    } 
}); 

所以它是做什么的基本上是,如果e是你想切换类元素,如果被点击e也是那么该类西港岛线不切换否则会。

+0

查看更新的答案。 – void 2015-02-23 08:08:39

+0

嗨,我确定这可行,但它禁用了主开关按钮上的开放功能,所以我无法折叠菜单。 – micknt 2015-02-23 08:14:26

+0

主切换按钮的类是什么? – void 2015-02-23 08:44:16

1

所以解决方案应该是,如果你点击容器内的任何地方点击处理程序应该什么都不做,只是返回。但是如果点击在容器外面,它应该关闭它。

下面是可能对您有帮助的点击处理程序代码。

$(document).click(function(e) { 
     var node = e.target; 
     // loop through ancestor nodes to check if the click is inside container. 
     // If yes then return from the handler method without doing anything 
     while(node.parentNode) { 
     if (node === container) { 
      return; 
     } 
     node = node.parentNode; 
     } 

     container.removeClass('active') 
    });