在外部点击关闭侧边栏 [英] Close sidebar on click outside

查看:62
本文介绍了在外部点击关闭侧边栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个Bootstrap示例工作一个站点,并在侧边栏导航中有一个简单的幻灯片.

I'm working a site using this Bootstrap example, with a simple slide in sidebar navigation.

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

它稍作修改,所以我有一个菜单打开按钮:

It is slightly modified, so I have a button for the menu to open:

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

以及用于关闭菜单的按钮:

And a button for the menu to close:

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

我想添加功能,因此如果我单击侧边栏外部的任何位置,它将关闭.到目前为止,我有这个:

I want to add functionality, so it will close if I click anywhere outside the sidebar. So far I have this:

// 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");
            }
     });

但是,似乎以这种方式删除了活动"类.

But it seems to remove the "active" class this way.

最诚挚的问候.

推荐答案

所以解决方案应该是,如果您在容器内的任何位置单击,单击处理程序将不执行任何操作而只是返回.但是,如果单击位于容器外部,则应将其关闭.

So the solution should be that if you click anywhere inside the container the click handler should do nothing and just return. But if the click is outside the container then it should close it.

下面是可能会帮助您的点击处理程序代码.

Below is the click handler code which might help you.

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

这篇关于在外部点击关闭侧边栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆