2014-06-05 207 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 

    } 
);