我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
我有一些HTML菜单,当用户单击这些菜单的头部时,我会完全显示这些菜单。当用户在菜单区域外单击时,我希望隐藏这些元素。
jQuery是否可以实现这样的功能?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
当前回答
这是我的代码:
// Listen to every click
$('html').click(function(event) {
if ( $('#mypopupmenu').is(':visible') ) {
if (event.target.id != 'click_this_to_show_mypopupmenu') {
$('#mypopupmenu').hide();
}
}
});
// Listen to selector's clicks
$('#click_this_to_show_mypopupmenu').click(function() {
// If the menu is visible, and you clicked the selector again we need to hide
if ( $('#mypopupmenu').is(':visible') {
$('#mypopupmenu').hide();
return true;
}
// Else we need to show the popup menu
$('#mypopupmenu').show();
});
其他回答
我认为最好的方法是这样做。
$(document).on("click", function(event) {
clickedtarget = $(event.target).closest('#menuscontainer');
$("#menuscontainer").not(clickedtarget).hide();
});
这种类型的解决方案很容易适用于多个菜单以及通过javascript动态添加的菜单。基本上,它只允许您单击文档中的任何位置,并检查您单击的元素,并选择最接近的“#菜单容器”。然后它会隐藏所有菜单容器,但不包括您单击的菜单容器。
不确定菜单是如何构建的,但可以在JSFiddle中复制我的代码。这是一个非常简单但功能全面的菜单/模式系统。您需要做的就是构建html菜单,代码将为您完成这项工作。
https://jsfiddle.net/zs6anrn7/
使用可访问性焦点
这里有一个答案说(非常正确),关注点击事件是一个可访问性问题,因为我们想迎合键盘用户。在这里使用focusout事件是正确的,但它可以比其他答案(以及纯JavaScript)简单得多:
更简单的方法是:
使用focusout的“问题”是,如果对话框/模式/菜单中的某个元素由于“内部”的原因而失去焦点,则事件仍然会被激发。我们可以通过查看event.relatedTarget(它告诉我们哪个元素将获得焦点)来检查情况是否并非如此。
dialog = document.getElementById("dialogElement")
dialog.addEventListener("focusout", function (event) {
if (
// We are still inside the dialog so don't close
dialog.contains(event.relatedTarget) ||
// We have switched to another tab so probably don't want to close
!document.hasFocus()
) {
return;
}
dialog.close(); // Or whatever logic you want to use to close
});
上面有一个小错误,那就是relatedTarget可能为空。如果用户在对话框外单击,这很好,但如果用户在对话内单击,而对话框恰好不可聚焦,则会出现问题。要解决此问题,必须确保将tabIndex设置为0,以便对话框可聚焦。
我已经使用了下面的脚本并完成了jQuery。
jQuery(document).click(function(e) {
var target = e.target; //target div recorded
if (!jQuery(target).is('#tobehide') ) {
jQuery(this).fadeOut(); //if the click element is not the above id will hide
}
})
下面是HTML代码
<div class="main-container">
<div> Hello I am the title</div>
<div class="tobehide">I will hide when you click outside of me</div>
</div>
你可以在这里阅读教程
投票选出最受欢迎的答案,但添加
&& (e.target != $('html').get(0)) // ignore the scrollbar
因此,单击滚动条不会隐藏目标元素。
这是一个经典的例子,对HTML进行调整将是更好的解决方案。为什么不在不包含菜单项的元素上设置单击?那么您不需要添加传播。
$('.header, .footer, .main-content').click(function() {
//Hide the menus if visible
});