如何检测元素外的点击? [英] How do I detect a click outside an element?

查看:26
本文介绍了如何检测元素外的点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 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
});

推荐答案

注意:使用 stopPropagation 是应该避免的,因为它会破坏 DOM 中的正常事件流.有关详细信息,请参阅这篇 CSS 技巧文章.考虑改用这种方法.

Note: Using stopPropagation is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆