简体   繁体   English

让点击事件通过一个元素而不删除该元素的指针事件

[英]Have click event go through an element without removing that element's pointer-event

I have an absolute positioned div that is above another relative positioned div.我有一个绝对定位的 div,它位于另一个相对定位的 div 之上。 They are both separate divs.它们都是独立的 div。

What I'm trying to do is: When I click on the absolute positioned div, I want to register that click and I want that click to go through it and register on the div below it.我想做的是:当我点击绝对定位的 div 时,我想注册该点击,我希望该点击通过它并在其下方的 div 上注册。

Using CSS's pointer-events: none;使用 CSS 的pointer-events: none; on the top div doesn't work because then I will not be able to register a click on it.在顶部的 div 上不起作用,因为那样我将无法注册对它的点击。

Is this even posible?这甚至可能吗?

In summary: I need a way to have an event go through an element without removing that element's event listener.总结:我需要一种方法让事件通过元素而不删除该元素的事件侦听器。

You can do it nested and the bubbling will do it automatically.您可以嵌套进行,冒泡会自动进行。

https://javascript.info/bubbling-and-capturing https://javascript.info/冒泡和捕获

When div#1 is clicked, you check if div#2 is under div#1 using elementsFromPoint method.单击div#1时,您使用elementsFromPoint方法检查div#2是否在div#1下。
If yes, you create and dispatch another click event on div#2 .如果是,您将在div#2上创建并发送另一个点击事件。

 document.addEventListener('click', e => { console.log(e.target.id); if (e.target.id === 'one') { const two = [...document.elementsFromPoint(e.clientX, e.clientY)].find(el => el.id === 'two'); if (two) { const clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent('click', ,0, ,0, window. 1, e.screenX, e.screenY, e.clientX, e,clientY, ,1, ,1; .1; !1, 0, null); two.dispatchEvent(clickEvent); } } })
 #one, #two { position:absolute; z-index:0; width:150px; height:150px; background:#f009; transform: rotateZ(30deg); } #two { z-index:-1; left:100px; background:#00f9; transform:rotate(45deg); } /* ignore th following */.as-console-wrapper { left:50%;important: top;0: max-height;100% !important; }
 <div id="one"></div> <div id="two"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM