简体   繁体   English

Javascript鼠标事件拦截

[英]Javascript mouse event interception

I'm currently facing a problem with Javascript and the mouse event onmouseover :我目前面临着 Javascript 和鼠标事件onmouseover

  • I've got a first element (svg rectangle) which call a function when mouse is over我有一个第一个元素(svg 矩形),它在鼠标悬停时调用一个函数
  • I've got a second element (png image) above this rect (but smaller than the rect)我在这个矩形上方有第二个元素(png 图像)(但比矩形小)

And the problem is that when the mouse is over the image, the rect doesn't call the function.问题是当鼠标悬停在图像上时,rect 不会调用该函数。
It's like the image is intercepting the event to do nothing with it.这就像图像正在拦截事件而不对其做任何事情。

I know I could add the event to the image too to solve the problem but is there any way to make the image kind of "transparent" for the mouse event and to transfer the mouseover event to the underneath element ?我知道我也可以将事件添加到图像中来解决问题,但是有什么方法可以使鼠标事件的图像“透明”并将鼠标mouseover事件传输到下面的元素?

There is no standard solution for this issue.这个问题没有标准的解决方案。 You can use jQuery mouseenter/mouseleave events to solve that, or you have to code a function to detect the dimensions and coords of the box and check the mouse position by yourself.您可以使用 jQuery mouseenter/mouseleave 事件来解决这个问题,或者您必须编写一个函数来检测框的尺寸和坐标并自己检查鼠标位置。

Take a look here for an example: JavaScript mouseover/mouseout issue with child element看看这里的一个例子: JavaScript mouseover/mouseout issue with child element

You might want to try the CSS property pointer-events:您可能想尝试 CSS 属性指针事件:

img.overlay {
   pointer-events: none;
}

"The CSS property pointer-events allows authors to control under what circumstances (if any) a particular graphic element can become the target of mouse events. When this property is unspecified, the same characteristics of the visiblePainted value apply to SVG content. “CSS 属性 pointer-events 允许作者控制在什么情况下(如果有)特定图形元素可以成为鼠标事件的目标。当未指定此属性时,visiblePainted 值的相同特征适用于 SVG 内容。

In addition to indicating that the element is not the target of mouse events, the value none instructs the mouse event to go "through" the element and target whatever is "underneath" that element instead." ( Source: MDN )除了指示该元素不是鼠标事件的目标之外,值 none 指示鼠标事件“通过”该元素并以该元素“下方”的任何内容作为目标。”(来源:MDN

I've found a solution : i create another transparent rectangle above the two other elements to capture the event.我找到了一个解决方案:我在其他两个元素上方创建另一个透明矩形来捕获事件。 The final rectangle moves at the same time as the first giving the illusion that the first one is catching the mouse event.最后一个矩形与第一个矩形同时移动,给人一种错觉,即第一个矩形正在捕捉鼠标事件。

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

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