文档单击以隐藏菜单

时间:2011-12-01 23:32:15

标签: javascript jquery

当我单击菜单外的文档时,我的文档点击功能没有隐藏我的菜单。当我单击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 个答案:

答案 0 :(得分:2)

我遇到了类似的问题,并使用以下代码解决了这个问题:

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

代替您的$(document).not(..代码。

答案 1 :(得分: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/