我正在使用 jQuery 开发一个简单的下拉菜单。当用户按下触发区域时,它将切换下拉区域。我的问题是如何在下拉菜单之外设置点击事件以关闭下拉菜单?
jQuery 下拉菜单通过单击外部关闭
IT技术
javascript
jquery
drop-down-menu
2021-02-07 22:30:34
6个回答
您可以告诉任何在 DOM 上一直冒泡的单击以隐藏下拉列表,以及任何使其到达下拉列表的父级的单击以停止冒泡。
/* Anything that gets to the document
will hide the dropdown */
$(document).click(function(){
$("#dropdown").hide();
});
/* Clicks within the dropdown won't make
it past the dropdown itself */
$("#dropdown").click(function(e){
e.stopPropagation();
});
如何在下拉菜单之外设置点击事件以关闭下拉菜单?这是代码
$(document).click(function (e) {
e.stopPropagation();
var container = $(".dropDown");
//check if the clicked area is dropDown or not
if (container.has(e.target).length === 0) {
$('.subMenu').hide();
}
})
在某些特定元素中停止事件传播可能会变得危险,因为它可能会阻止其他某些脚本运行。所以检查触发是否来自函数内部的排除区域。
$(document).on('click', function(event) {
if (!$(event.target).closest('#menucontainer').length) {
// Hide the menus.
}
});
这里的函数是在点击文档时启动的,但它排除了#menucontainer 的触发。详情https://css-tricks.com/dangers-stopping-event-propagation/
您需要将点击事件附加到某个元素。如果页面上有很多其他元素,您不希望将点击事件附加到所有元素。
一种可能的方法是在下拉菜单下方但在页面上的所有其他元素上方创建一个透明的 div。您将在显示下拉菜单时显示它。让元素有一个隐藏下拉菜单和透明 div 的点击处理程序。
$('#clickCatcher').click(function () {
$('#dropContainer').hide();
$(this).hide();
});
#dropContainer { z-index: 101; ... }
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dropDown"></div>
<div id="clickCatcher"></div>
另一个有效的多下拉示例 https://jsfiddle.net/vgjddv6u/