[英]How to catch event on a parent div?
I would like to ask: 我想问一下:
Basically the group should visually cover the two other divs, so when I click inside the are covered by the group, only group div should detect mousedown. 基本上,该组应该在视觉上覆盖另外两个div,因此,当我在该组所覆盖的区域内单击时,只有div组才能检测到mousedown。
Notes: I cannot change HTML structure. 注意:我无法更改HTML结构。
document.getElementById('group').addEventListener('click', function(event) { event.stopPropagation(); alert('click on: ' + event.target.id); });
#group { position: absolute; width: 250px; height: 250px; background-color: yellow; z-index: 2; opacity: 0.5; } #a { position: absolute; left: 80px; width: 50px; height: 50px; margin: 10px; background-color: blue; z-index: 0; } #b { position: absolute; width: 50px; height: 50px; margin: 10px; background-color: blue; z-index: 0; }
<div id="group"> <div id="a">A</div> <div id="b">B</div> </div>
Use opacity 0 for the children. 为孩子们使用不透明度0。
Use event.currentTarget
instead of event.target
. 使用event.currentTarget
而不是event.target
。
With this config children are actually above groups
, but are not visible and events are caught by groups
elem, not children. 使用此配置,子级实际上位于groups
之上,但不可见,并且事件由groups
elem而非子级捕获。
document.getElementById('group').addEventListener('click', function(event) { event.stopPropagation(); alert('click on: ' + event.currentTarget.id); });
#group { position: relative; width: 250px; height: 250px; background-color: yellow; z-index: 2; opacity: 0.5; } #a { position: relative; left: 80px; width: 50px; height: 50px; margin: 10px; background-color: blue; z-index: 0; opacity: 0 } #b { position: relative; width: 50px; height: 50px; margin: 10px; background-color: blue; z-index: 0; opacity: 0; }
<div id="group"> <div id="a">A</div> <div id="b">B</div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.