我有相应的按钮和div,如果单击一个按钮,就会显示一个菜单,而任何其他可能打开的菜单都会被隐藏。
如果用户单击页面上的其他位置,我也会隐藏这些菜单,但是我正在使用的mouseup事件可以防止用户再次单击按钮元素时隐藏菜单。
$(document).on("click", ".some-btn", function(e) { //toggles the dropdown menu
e.preventDefault();
var $this = $(this).parent().find('.dropdown-menu');
$(this).nextAll('dropdown-menu').first().toggle();
$(".actions-dropdown-menu").not($this).hide();
});
$(document).mouseup(function (e){ //hides the menu if user clicks elsewhere
var dropdown = $('.dropdown-menu');
if(!dropdown.is(e.target) && dropdown.has(e.target).length === 0){
dropdown.hide();
}
});按钮/菜单:
<button class="some-btn"></button>
<ul class="dropdown-menu" style="display: none;">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
<button class="some-btn"></button>
<ul class="dropdown-menu" style="display: none;">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>我已经尝试提取条件以检查下拉列表是否不是target,但仍然没有成功
发布于 2015-07-20 04:32:31
我在mouseup上检查错误的元素。应该一直在检查按钮而不是菜单。现在可以正常工作了:
$(document).mouseup(function (e){ //hides the menu if user clicks elsewhere
var button = $('.some-btn');
if(!button .is(e.target) && button.has(e.target).length === 0){
$('.dropdown-menu').hide();
}
});https://stackoverflow.com/questions/31505552
复制相似问题