2014-06-05 210 views
1

我一直在工作一个响应式网站和平板电脑成为下拉菜单,但我需要当点击是在文档之外的菜单关闭,(也需要鼠标箭头更改它是正常的形式),我无法找到一个方法来做到这一点,这里是我一直在使用的代码:点击外部菜单关闭jquery

JQUERY

$(function() { 

    var btn_mobile = $('#nav-mobile'), 
     menu = $('#menu').find('ul'); 

    btn_mobile.on('click', function (e) { 
     e.preventDefault(); 
     e.stopPropagation(); 


     var el = $(this); 

     el.toggleClass('nav-active'); 
     menu.toggleClass('open-menu'); 

    }) 

}); 

HTML

<nav id="menu"><a class="nav-mobile" id="nav-mobile" href="#">MENU</a> 
<ul> 
    <li><a href="index.html">Home</a></li> 
    <li><a href="work.html">Work</a></li> 
    <li><a href="about.html">About</a></li> 
    <li><a href="contact.html">Contact</a></li> 
</ul> 

局部CSS(片剂)

#nav-mobile{ 
    display: none; 
    background: url(../images/menu-icons.svg) no-repeat 42px -2px; 
    float: right; 
    width:75px; 
    height:35px; 
    padding-top:9px; 
    position: absolute; 
    right:0; 
    top:0; 
    font-weight:bold; 

} 

#nav-mobile.nav-active{opacity: 1; background: url(../images/menu-icons.svg) no-repeat 42px -48px;} 

/* TABLET */ 
    #nav-mobile{display: block; } 
    #menu{margin-top:0px;width: 100%;float: none;padding-top:55px;} 
    #menu ul{ 
    max-height: 0; 
    overflow: hidden; 
    text-align:center; 
    position:relative; 
    z-index:500; 
    transition: max-height .5s, box-shadow 1.2s, opacity 0.5s; 
    opacity:0; 
    margin:0 -3.2%; 
    } 
    #menu li{background:#fff;border-bottom: 1px solid #ececec;float: none;} 
    #menu li a{padding: 12px 0;height: auto;width:100%; text-transform:uppercase;} 
    #menu li a:hover{background:#fbfbfb;} 
    #menu ul.open-menu{max-height: 400px;transition: max-height .5s, box-shadow 1.2s, opacity 0.5s; border-top: 1px solid #CCC; box-shadow: 0px 9000px 0px 9000px rgba(0,0,0,0.15); opacity:1; } 

感谢您的关注!。

+0

您可以创建可见DIV填充菜单打开时,整个文档。确保div的z-index小于菜单z-index。并添加到该div的点击处理程序。如果有人点击它,只需关闭菜单。 – Hardy

+1

可能的重复[如何检测单元外的点击?](http://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) –

回答

0

你可以使用你的菜单后面的透明层,将覆盖整个页面(manipuling的CSS的z-index)

在此图层上,您可以添加点击事件处理程序将隐藏菜单并更改箭头和“display:none;”本身。菜单下拉菜单会以“显示:块”回选择

时看看引导如何与情态动词处理它:http://getbootstrap.com/javascript/#modals

+0

谢谢非常!! :) – user3709158

0

查看jQuery中的hover(in,out)鼠标光标更改,并使用body :not['#nav..']选择器关闭菜单。

哈弗例如:

// Hover script 
btn_mobile.hover(
    function() { 
     // {Hover in of the menu} 
     // change the mouse here 
    }, 
    function() { // out 
     // {Hover out of the menu} 
     // change the mouse here 

    } 
);