如何检测元素外部的单击? [英] How do I detect a click outside an element?
问题描述
我有一些HTML菜单,当用户点击这些菜单的头部时,我会完全显示这些菜单。当用户点击菜单区域外时,我想隐藏这些元素。
I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
jQuery可以这样吗?
Is something like this possible with jQuery?
$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
推荐答案
注意:使用
stopEventPropagation()
是应该避免的,因为它会破坏DOM中的正常事件流。有关详细信息,请参阅本文。请考虑使用此方法
NOTE: Using
stopEventPropagation()
is something that should be avoided as it breaks normal event flow in the DOM. See this article for more information. Consider using this method instead
将单击事件附加到关闭窗口的文档正文。将单独的单击事件附加到容器,该容器停止传播到文档正文。
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
这篇关于如何检测元素外部的单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!