javascript d3.on("mouseover") 事件不适用于嵌套的 SVG 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17494930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:32:00  来源:igfitidea点击:

d3.on("mouseover") event does not work with nested SVG elements

javascripteventssvgd3.jsmouse

提问by user2279929

I have a nested set of elements (SVG). The root element is the graph, and the children are elements in the graph (lines, axis, etc.). Simplified example:

我有一组嵌套的元素 (SVG)。根元素是图形,子元素是图形中的元素(线、轴等)。简化示例:

<g transform="translate(80,10)" id="mainGraph">
    <g class="Line">
        <path d="....."></path>
    </g>
</g>

My problem is that if I bind a mouseover/mousemove event (with D3.on("mouseover") for example) to the mainGraph element, it only triggers if I move the mouse over one of the child elements.

我的问题是,如果我将鼠标悬停/鼠标移动事件(例如 D3.on("mouseover"))绑定到 mainGraph 元素,它只会在我将鼠标移动到子元素之一上时触发。

One of the things I read is that there is priority of later elements, so I added .style("pointer-events","none") to all child elements, but that didn't work.

我读到的一件事是后面的元素有优先级,所以我向所有子元素添加了 .style("pointer-events","none") ,但这不起作用。

回答by explunit

One approach is to add a rectangle filling the whole surface as the first element to catch mouse events that are not caught by elements added later:

一种方法是添加一个填充整个表面的矩形作为第一个元素,以捕获后来添加的元素未捕获的鼠标事件:

something.append('svg:rect')
  .attr('width', width) // the whole width of g/svg
  .attr('height', height) // the whole heigh of g/svg
  .attr('fill', 'none')
  .attr('pointer-events', 'all')
  .on('mouseover', function() {
      // do something
    }     
  });

I believe the <g>element (mainGraph in your example) is just a container, not an actual shape that can receive mouse events.

我相信<g>元素(在您的示例中为 mainGraph)只是一个容器,而不是可以接收鼠标事件的实际形状。

You might be able to add the mouse event listener on the svg element itself, but I don't think the <g>will work.

您也许可以在 svg 元素本身上添加鼠标事件侦听器,但我认为这<g>行不通。

回答by Ketan

Apart from using a rectelement, it should have a CSS property set like this pointer-events: all;for the events to be triggered.

除了使用rect元素之外,它还应该pointer-events: all;为要触发的事件设置一个像这样的 CSS 属性。

回答by Mukesh Kumar Suman

I also face the same problems.
The solution is to add the css property to parent element

我也面临同样的问题。
解决方法是将css属性添加到父元素

pointer-events: stroke;

or

或者

pointer-events: visibleStroke;