2

当我单击 Google 等更多选项时,我需要一个下拉菜单。它正在工作,但是当我在 div 外部单击时,它处于非活动状态。当我在 div 之外单击时,我想切换菜单。

我的JavaScript:

$('#other').click(function() {
    $(this).toggleClass('active');
    $(this).next('.dropdown').toggle();
    return false;
});
$('.dropdown a').click(function() {
    return false;
});
4

2 回答 2

0

您可以订阅 document.click 并关闭事件处理程序中的菜单。从下拉菜单中停止事件的传播,以便在下拉菜单内单击时不会关闭。

$('.dropdown').click(function (event) {
    event.stopPropagation();
    return false;
});

$(document).click(function (event) {
    if ($('.dropdown').is(':visible')) {
        $('.dropdown').toggle();
        $('#other').toggleClass('active');
    }
});

你的小提琴更新了。

于 2013-08-02T12:53:57.820 回答
0

从这个答案中得到一个想法

$(document).mouseup(function (e)
{
    var container = $("#other");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.toggle();
    }
});

我的想法,它不应该切换,最好显示/隐藏机制。

于 2013-08-02T12:57:28.747 回答