【问题标题】:document click to hide menu文档点击隐藏菜单
【发布时间】:2011-12-02 07:41:56
【问题描述】:

当我点击菜单外的文档时,我的文档点击功能没有隐藏我的菜单。当我单击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() });
 })

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我遇到了类似的问题,用下面的代码解决了:

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

    而不是您的 $(document).not(.. 代码。

    【讨论】:

    • 使用对上下文菜单对象的引用,而不是指示上下文菜单是否可见的布尔值。像上面一样使用它,但它也会告诉你 哪个 菜单需要隐藏,当有多个上下文菜单时,这非常方便。这不会干扰菜单项上的点击事件。
    【解决方案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/

    【讨论】:

    • 有趣的解决方案,很有启发性。我个人使用一个全局变量 contextMenu,它包含对包装在 jquery 对象中的活动 contextMenu 的引用,因为这不仅告诉我需要隐藏上下文菜单,它还告诉我 which 菜单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多