jquery中的点击
在 jquery 中进行点击的最简单方法是什么,如果单击 div 框外部的任何位置,则该 div 框会隐藏。
What is the easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我不喜欢使用 stopPropagation 的解决方案,因为我经常使用事件冒泡来管理各种链接。我不想担心如果盒子存在的话它们可能会停止工作。我的选择看起来像这样:
has
函数过滤选择并仅当元素包含作为参数传递的元素时才返回元素(您也可以使用选择器字符串,但这与此处无关)。如果点击位于框外,则length
将为0
,因此条件将通过并且框将被隐藏。这应该通过设置一个布尔值来优化,以确定该框当前是否可见,并且仅在当前可见时才执行
has
调用。I don't like the solutions that use
stopPropagation
because often I am using event bubbling to manage various links. I don't want to have to worry that they might stop working if the box exists. My choice would look something like this:The
has
function filters the selection and returns elements only if they contain the element passed as the parameter (you can also use a selector string, but that isn't relevant here). If the click was outside the box,length
will be0
so the conditional will pass and the box will be hidden.This should be optimised by setting a boolean value for whether the box is currently visible and only doing the
has
call if it is currently visible.像这样:
在这里摆弄:http://jsfiddle.net/XYbmE/3/< /a>
like this:
fiddle here: http://jsfiddle.net/XYbmE/3/
这是有效的,因为如果您在内部单击,#box 将首先收到单击事件。由于传播已停止,附加到主体的处理程序将不会收到它,因此除非您在框外单击,否则框不会关闭。
如果您希望它立即隐藏,请使用
.hide()
我从 如何检测元素外部的点击?
This works because #box will receive the click event first if you clicked inside. Since propagation is stopped, the handler attached to body won't receive it so the box won't be closed unless you clicked outside of the box.
If you want it to hide immediately, use
.hide()
I've got the stopPropagation() trick from How do I detect a click outside an element?
我建议使用这个库 https://github.com/gsantiago/jquery-clickout。太棒了!
I recommend use this lib https://github.com/gsantiago/jquery-clickout. It's awesome!
我知道 jQuery 有 "focusout" 表单元素事件,不确定是否可以使用对于一个
I know that jQuery has the "focusout" event for form elements, not sure if it could maybe be used for a
将单击函数绑定到文档本身:
然后将函数绑定到 div 本身上的同一事件并返回 false,以便该事件不会冒泡到文档。
Bind a click function to the document itself:
Then bind a function to the same event on the div itself and return false so the event will not bubble up to the document.
这是我的解决方案
Heres my solution