处理 z-index 图层上的点击事件
我正在构建的地图应用程序中有 2 个 z-index 图层。 当我单击图层进行放大时,我遇到了问题。单击处理程序位于底层 z-index 图层上,我不希望它在单击上方图层中的控件时触发。
我遇到的问题是,无论如何,事件都会引发,但当单击顶层上的某些内容时,事件的originalTarget 属性不是底层中的图像。 有办法改变这个吗?
I have 2 z-index layers in a map application I'm building. I have a problem when I click on the layers to zoom in. The click handler is on the underlying z-index layer and I don't want it to fire when a control in the overlying layer is clicked.
The problem i have is that the event gets raised no matter what but the originalTarget property of the event is not the image in the underlying layer when something on the top layer is clicked. Is there anyway to change this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这称为事件冒泡,您可以使用
event.stopPropagation()
方法(IE 中的event.cancelBubble()
)来控制它。 您还可以通过从元素上的 onwhatever 属性调用的处理程序返回 true/false 来控制它。 这是一个棘手的主题,所以我建议您做一些研究。信息:cancelBubble、stopPropagation
It's called event-bubbling, and you can control it with the
event.stopPropagation()
method (event.cancelBubble()
in IE). You can also control it by returning true/false from handlers called by onwhatever attributes on elements. It's a tricky subject so I suggest you do some research.Info: cancelBubble, stopPropagation
尽管这不能直接解决问题,但在更合适的解决方案出现之前,这可能是一种可行的解决方法。
编写一个名为 onClick 的函数,并让该函数足够聪明地知道是谁调用了它。 然后,该函数根据点击它的人采取适当的操作。 您可以向其发送几乎任何独特的内容,然后使用开关。
简化示例:
Although this does not address the problem directly it may be a viable workaround until a more fitting solution presents itself.
Write a single function to be called onClick and allow the function enough smarts to know who called it. The function then takes the appropriate action based upon who clicked it. You could send it pretty much anything that would be unique and then use a switch.
simplified example :
或者,另一种解决方法是在您不想单击的 div 上使用 CSS 属性
pointer-events: none;
,然后在更深的嵌套组件上使用pointer-events: all;< /code> 您希望能够单击的 div 上。
这样您就可以将事件传播到所需的组件(如果有原因您不能使用其他解决方案)
or, one more workaround could be using CSS property
pointer-events: none;
on div's you don't want to click, and then on deeper nested components usepointer-events: all;
on div's you want to be able to click.This way you could propagate event to desired component (if there is a reason you cannot use other solution)
我认为最好的做法是当控件移动到上层时分离事件处理程序,当控件返回到下层时,您可以重新附加事件。
I think the best practice is to detach the event handler when the control moves to the upper layer and when the control gets back to the lower layer, you can reattach the events.
的元素
优先级为具有较大 z-index http://api.jquery.com/event 。停止传播/
priority to the element who has the great z-index
http://api.jquery.com/event.stopPropagation/