如何将点击传播到光标下的所有div? [英] How to propagate a click to all divs under cursor?
问题描述
我有一堆的divs绝对在彼此的顶部。当我将点击事件绑定到所有用户时,只有顶层响应。
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?
推荐答案
使用FelixKling的建议使用文档.elementFromPoint()
和Amberlamps的小调,并使用jQuery的DOM交互,我结束了以下:
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 :
$divs = $("div").on('click.passThrough', function (e, ee) {
var $el = $(this).hide();
try {
console.log($el.text());//or console.log(...) or whatever
ee = ee || {
pageX: e.pageX,
pageY: e.pageY
};
var next = document.elementFromPoint(ee.pageX, ee.pageY);
next = (next.nodeType == 3) ? next.parentNode : next //Opera
$(next).trigger('click.passThrough', ee);
} catch (err) {
console.log("click.passThrough failed: " + err.message);
} finally {
$el.show();
}
});
DEMO
try / catch / finally
两种机制允许点击事件通过或不通过:
Two mechanisms allow the click event to be passed through or not :
- 将处理程序仅附加到所选元素(标准jQuery)。
- 命名点击事件,
click.passThrough
类似于event.stopPropagation()
。
- attaching the handler to only selected elements (standard jQuery).
- namespacing the click event,
click.passThrough
analogous toevent.stopPropagation()
.
单独地或组合地,这些机制在控制passThrough行为的附接和传播方面提供一些灵活性。例如,在DEMO中,尝试从b元素中删除类 p
,看看传播行为是如何改变的。
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 :
- 允许程序化附加应用程序特定行为
- 程序化禁止passThrough传播,类似于
event.stopPropagation()
。
- allow for programmatic attachment of app-specific behaviour
- allow for programmatic inhibition of "passThrough" propagation, analogous to
event.stopPropagation()
.
通过在jQuery中建立一个 clickPassthrough
事件和底层的passThrough行为,可以实现这两个目标,但需要更多的工作来实现。也许有人想去。
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.
这篇关于如何将点击传播到光标下的所有div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!