I have a bunch of divs postioned absolutely on top of each other. When I bind a click event to all of them, only the top div responds. How can I send the event to all divs under the cursor?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Taking FelixKling's suggestion to use
document.elementFromPoint()
and Amberlamps's fiddle, and employing jQuery for the DOM interactions, I ended up with the following :DEMO
try/catch/finally
is used to ensure elements are shown again, even if an error occurs.Two mechanisms allow the click event to be passed through or not :
click.passThrough
analogous toevent.stopPropagation()
.Separately or in combination, these mechanisms offer some flexibility in controlling the attachment and propagation of "passThrough" behaviour. For example, in the DEMO, try removing class
p
from the "b" element and see how the propagation behaviour has changed.As it stands, the code needs to be edited to get different application-level behaviour. A more generalized solution would :
event.stopPropagation()
.Both of these ambitions might be achieved by establishing a
clickPassthrough
event in jQuery, with underlying "passThrough" behaviour, but more work would be involved to achieve that. Maybe someone would like to have a go.A simple way could be to use elementFromPoint():
http://jsfiddle.net/SpUeN/1/
This is not as easy as you might think. This is a solution that I came up with. I only tested it in Chrome and I did not use any framework.
The following snippet is just for add a click event to every
div
in the document, that outputs its class name when triggered.Attaching a click event to the body element so that every single click event is noticed by our script.
Iterate through all divs that you want to check (you might want to adjust here to your preferred range of divs). Generate their computed style and check whether the mouse coordinates are within the range of the div´s position plus its width and height. Do not trigger click event when the div is our source element because the click event has already been fired by then.
CSS:
HTML:
I also added a jsFiddle
If you are stacking elements absolutely it may be simpler to stack them all in a positioned container, and handle the events from this parent. You can then manipulate its children without having to measure anything.