如何让点击事件仅在父 DIV 上触发,而不是在子 DIV 上触发?
我有一个带有分类 foobar
的 DIV,以及该 DIV 内的一些未分类的 DIV,但我认为它们继承了 foobar
类:
$('.foobar').on('click', function() { /*...do stuff...*/ });
我希望它能够启动仅当单击 DIV 中的某处而不是其子 DIV 时。
I have a DIV with a classed foobar
, and a few DIVs inside that DIV that are unclassed, but I suppose they are inheriting the foobar
class:
$('.foobar').on('click', function() { /*...do stuff...*/ });
I want that to fire off only when clicking somewhere in the DIV but not on its children DIVs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我遇到了同样的问题并提出了这个解决方案(基于其他答案)
基本上它说如果目标是 div 然后运行代码,否则什么也不做(不要隐藏它)
I had the same problem and came up with this solution (based on the other answers)
Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)
您可以使用 event.currentTarget。它只会执行点击事件的元素谁得到了事件。
You can use event.currentTarget. It will do click event only elemnt who got event.
如果您无法使用
pointer-events: none;
并且面向现代浏览器,您可以使用composedPath
来检测对对象的直接点击,如下所示:您可以阅读更多关于这里的composedPath:
https://developer.mozilla.org/en-US/文档/Web/API/Event/composedPath
If you can't use
pointer-events: none;
and are targeting modern browsers you can usecomposedPath
to detect a direct click on the object like so:You can read more about composedPath here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
当你定义一个事件时,该事件有一个属性
this
。该属性表示事件被分配到的 DOMElement。要检查触发事件的元素,请使用e.target
。由于事件是在元素的子元素中继承的,因此检查目标是否
When you define an event, the event has a property
this
. This property represents the DOMElement to which the event was assigned.To check the element in which the event was fired, usee.target
.Since events are inherited in the children of an element, check if the target
我的情况类似,但这是当您有几个
foobar
-s 时,并且您只想关闭一个 - 每次点击:查找父案例
查找子案例
My case is similar but this is occasion when you have few
foobar
-s, and you want to close only one - per one click:Find parent case
Find child case
如果
e.target
与this
是相同的元素,则您没有点击后代。If the
e.target
is the same element asthis
, you've not clicked on a descendant.我没有得到公认的工作答案,但这似乎可以解决问题,至少在普通 JS 中是这样。
I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.
如果您不介意只针对较新的浏览器,还有另一种可行的方法。只需将 CSS 添加
到您想要捕获点击的 div 的任何子级即可。这是支持表
http://caniuse.com/#feat=pointer-events
There's another way that works if you don't mind only targeting newer browsers. Just add the CSS
to any children of the div you want to capture the click. Here's the support tables
http://caniuse.com/#feat=pointer-events
您可以使用对您有利的冒泡:
You can use bubbling in your favor:
这将停止
.foobar
元素的任何子元素上的click
事件的传播(冒泡),因此该事件不会到达.foobar
元素来触发其事件处理程序。这是一个演示: http://jsfiddle.net/bQQJP/
This will stop the propagation (bubbling) of the
click
event on any of the children element(s) of the.foobar
element(s) so the event won't reach the.foobar
element(s) to fire their event handler(s).Here is a demo: http://jsfiddle.net/bQQJP/