我有一个表格,每行都有一个下拉按钮。 当您单击该按钮时,将打开一个下拉列表,当您在该区域外单击时,该下拉列表将关闭。 如何保证在下拉列表区域点击时不关闭?以及如何确保当你点击另一个带有下拉列表的按钮时,之前的下拉列表是关闭的?
$(".dropdown").click(function(e) {
$(this).find(".dropdown-menu").slideToggle();
});
$(document).on("click", function(event) {
var $trigger = $(".dropdown");
if ($trigger !== event.target && !$trigger.has(event.target).length) {
$(".dropdown-menu").slideUp("fast");
}
});
.dropdown {
display: inline-block;
position: relative;
}
.dropdown-menu {
text-align: center;
font-size: 14px;
background-color: #ffffff;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<li class="dropdown">
<button></button>
<ul class="dropdown-menu">
<li></li>
<li></li>
</ul>
</li>
</td>
最佳答案
如下所示更新您的 $(".dropdown").click(function(e) { ... }
。
- 使用 slideDown 而不是 slideToggle 将其设置为始终打开。
- 选择所有下拉菜单并使用
$(".dropdown-menu").not($(this).find(".dropdown-menu"))
和应用.slideUp("fast")
。
在下面试试。
$(".dropdown").click(function(e) {
// use slideDown instead of slideToggle to set it always open.
$(this).find(".dropdown-menu").slideDown();
// select all dropdown-menu and remove current dropdown-menu with .not
// hide other dropdowns.
$(".dropdown-menu").not($(this).find(".dropdown-menu")).slideUp("fast");
});
$(document).on("click", function(event) {
var $trigger = $(".dropdown");
if ($trigger !== event.target && !$trigger.has(event.target).length) {
$(".dropdown-menu").slideUp("fast");
}
});
$(".dropdown-menu").slideUp();
.dropdown {
display: inline-block;
position: relative;
}
.dropdown-menu {
text-align: center;
font-size: 14px;
background-color: #ffffff;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>
<li class="dropdown">
<button>open dropdown</button>
<ul class="dropdown-menu" style="display: none;">
<li>11</li>
<li>12</li>
</ul>
</li>
</td>
</tr>
<tr>
<td>2</td>
<td>
<li class="dropdown">
<button>open dropdown</button>
<ul class="dropdown-menu" style="display: none;">
<li>21</li>
<li>22</li>
</ul>
</li>
</td>
</tr>
</table>
关于javascript - 下拉列表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66167861/