2011-12-01 170 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的引用,因为这不仅告诉我一个需要隐藏的上下文菜单,它告诉我哪个*菜单。 –