[英]Close bootstrap dropdown only when mouse is clicked outside of dropdown
I have a bootstrap dropdown menu:我有一个引导下拉菜单:
<div class="dropdown>
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>
<ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>
Now the ul load the products on page load through ajax call.现在 ul 通过 ajax 调用在页面加载时加载产品。 The issue is when I click any product in the dropdown, the dropdown gets closed.问题是当我单击下拉列表中的任何产品时,下拉列表会关闭。 But I want to close dropdown only when mouse is clicked anywhere outside of the ul但是我只想在 ul 之外的任何地方单击鼠标时才关闭下拉菜单
Try something like this:尝试这样的事情:
$(document).click(function(e) {
// get the clicked element
$clicked = $(e.currentTarget);
// if the clicked element is not a descendent of the dropdown
if ($clicked.closest('.dropdown').length === 0) {
// close the dropdown
$('.dropdown').removeClass('open');
}
});
just place this script in your code只需将此脚本放在您的代码中
<script>
$(document).click(function() {
$(".dropdown").removeClass('open');
});
</script>
In 2021 you do it this way:在 2021 年,你这样做:
$('.dropdown').on({
"shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
"click": function(e) { // handles click event
console.log(e.target) // just to check which element is on top
if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
this.closable = false // do not close it
return;
} else {
this.closable=true; // else close it
}
},
"hide.bs.dropdown": function() { return this.closable; } // save state
});
}
Bootstrap 有一个内置的解决方案
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown" data-bs-auto-close="outside"><img ... \/><\/a><\/code>
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.