2011-12-01 171 views
1

當我點擊我的菜單之外的文檔時,我的文檔點擊功能沒有隱藏我的菜單。當我點擊img時,它會顯示菜單,當我再次點擊img時,它會隱藏它,但當我點擊文檔時,我希望它隱藏菜單,是否有人知道我做錯了什麼以及如何使它工作。文檔點擊隱藏菜單

var visible = false; 
var id = $(this).attr('id'); 

$(document).not('#' + id + ' div:eq(1)').click(function() { 
    if (visible) {    
     $('.dropdownlist .menu').hide(); 
     visible = false; 
    } 
});  


$(this).find('div:eq(1)').click(function (e) { 
    var menu = $(this).parent().find('.menu'); 

    if (!visible) { 
     menu.show(); 
     visible = true; 
    } else if (visible) { 
     menu.hide(); 
     visible = false; 
    } 
    menu.css({ 'left': $(this).position().left + $(this).width() - menu.find('ul').width(), 
       'top': $(this).position().top + $(this).height() }); 
}) 

回答

2

我有一個類似的問題,用下面的代碼解決了這個問題:

$("body").mouseup(function(){ 
    if (visible) { 
     $('.dropdownlist .menu').hide(); 
     visible = false; 
    } 
}); 

,而不是你$(document).not(..代碼。

+0

,與其合作三江源 – ONYX

+0

表示上下文菜單是否可見一個布爾值,請使用上下文菜單對象的引用。如上所述使用它,但它也告訴你*哪個菜單需要隱藏,當有幾個上下文菜單時這是超級方便的。這不會影響菜單項上的點擊事件。 –

2
//add event.stopPropagation() when the user clicks on a .menu element 
$('.menu').on('click', function (event) { 

    //.stopPropagation() will stop the event from bubbling up to the document 
    event.stopPropagation(); 
}); 

//add the click event handler to the image that will open/close .menu elements 
$('img').on('click', function (event) { 

    //we call .stopPropagation() again here so the document won't receive this event 
    event.stopPropagation(); 

    //cache .menu element 
    var $div = $('.menu'); 

    //this if statement determines if the .menu should be shown or hidden, in my example I'm animating its top property 
    if ($div.css('top') == '-50px') { 
     $div.stop().animate({top : 0}, 250); 
    } else { 
     $div.stop().animate({top : '-50px'}, 150); 
    } 
}); 

//add click event handler to the document to close the .menu 
$(document).on('click', function() { 
    $('div').stop().animate({top : '-50px'}, 150); 
}); 

的jsfiddle:http://jsfiddle.net/jasper/n5C9w/1/

+0

有趣的解決方案,非常具有啓發性。我個人使用一個全局變量contextMenu,它包含一個對包裝在jquery對象中的活動contextMenu的引用,因爲這不僅告訴我一個需要隱藏的上下文菜單,它告訴我哪個*菜單。 –