2013-08-02 160 views
2

当我点击Google等更多选项时,我需要一个下拉菜单。它正在工作,但是当我在div外部单击时它不活动。当我点击div外部时,我想切换菜单。onclick切换下拉按钮

我的javascript:

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

你可以给我们一个完整的工作示例(或不工作)与你到目前为止的尝试。一个jsfiddle会很好。剧本本身,不给我们很多工作。只有猜测。 – gmo

+0

此链接[jsfiddle demo](http://jsfiddle.net/marvanjaam/8dczj/) – marvan

回答

0

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

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

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

您的fiddle已更新。

+0

但是,随着...每次点击文档时,切换事件都会触发......即使您单击外面和菜单很近......将被打开。 – gmo

+0

可能要在文档点击处理程序中使用'.hide()'和'.removeClass('active');'。否则,单击页面上的任何其他位置将打开并关闭下拉菜单。 – Travesty3

+0

@Konstantin是兄弟。它正在工作。但是,只要您点击页面中的下拉菜单即可。但我想当我点击其他时间只有我想要主动显示下拉菜单 – marvan

0

有一个想法从这个answer

$(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(); 
    } 
}); 

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