我正在尝试构建一个下拉菜单。
点击屏幕上的任何其他位置时关闭。
没关系。
我无法在我使用的逻辑中找到错误,感谢任何帮助!
谢谢!
$
// Dropdown menu icon animation up/down toggle.
$('.dropbtn').on('click', function() {
$('#myDropdown').slideToggle();
$(this).find('i').toggleClass('fa-sort-up fa-sort-down')
});
// Dropdown menu up/down toggle.
$(document).mouseup(function(e) {
var container = $(".dropdownmenu");
if (!container.is(e.target)
&& container.has(e.target).length === 0
)
{
$("#myDropdown").slideUp();
$('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
}
});
HTML
<div class="dropdown">
<div class="dropdownmenu">
<button class="dropbtn main">Diet or Allergen Filter <i class="fa fa-sort-up" style="font-size:24px; line-height:0px; margin-left: 5px;"></i></button></div>
<div id="myDropdown" class="dropdown-content">
<a id="veganDiet" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegan2-1.png" style="width:40px; display:inline; height:20px; vertical-align:middle;"> Vegan</a>
<a id="vegetarianDietButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/vegetarian-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> Vegetarian</a>
<a id="noAddesSugarButton" class="dropbtn"><img src="http://www.padthai.decorolux.com/wp-content/uploads/2017/11/sugarfree-1.png" style="width:40px; height:20px; display:inline; vertical-align:middle;"> No Added Sugar</a>
</div>
</div>
此外,这是现场代码:
答案 0 :(得分:1)
在这里,试试这个
$(document).mouseup(function(e) {
//if you are clicking on the a tags inside #myDropdown stop
//propagation of the event up the DOM (prevent it from getting to 'document')
if($(e.target).is('#myDropdown a')){
e.stopPropagation();
}else{
$("#myDropdown").slideUp();
$('.dropbtn i').addClass('fa-sort-up').removeClass('fa-sort-down')
}
});
事件传播从内到外工作,当您点击触发其事件的元素,然后点击其父事件等等; e.stopPropagation()阻止了这种情况发生,因此如果您没有点击#myDropdown a
, mouseup 事件将只会转到文档。
尝试和LMK