D3.js - why mouseover and mouse out fired for each child elements?

前端 未结 2 2089
醉酒成梦
醉酒成梦 2021-02-07 11:37

I use d3.js to generate a svg circle with a text logo in mid of the circle. Here is the svg result.


  

        
相关标签:
2条回答
  • 2021-02-07 12:17

    You can prevent the text element receiving mouse events (and thus a mouseout event triggering when you move the mouse over it) by setting pointer-events to none:

    svg.select("#main").append("text")
       .attr("text-anchor", "middle")
       .attr("pointer-events", "none")
       .text(function(){ return "The movie title";});
    

    You probably also want to set the events on the circle and not on the g element:

    svg.select("#main").selectAll("circle")
       .data(circles).enter()
       .append("circle")
       .attr("r",function(d){return d.r})
       .attr("fill","#F0E8D0")
       .on("mouseover",function(){
         //code for transition
       })
       .on("mouseout",function(){
         //code for transition
       })
    
    0 讨论(0)
  • 2021-02-07 12:33

    An alternate solution is to use mouseenter and mouseleave instead of mouseover and mouseout.

    mouseenter is similar to mouseover except that it is not triggered when the pointer (mouse) is moved from one of listener's (circle in this case) descendants' physical space (text in this case) to its own physical space.

    Same reasoning for 'mouseleave'

    Source: https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter and https://developer.mozilla.org/en-US/docs/Web/Events/mouseleave

    0 讨论(0)
提交回复
热议问题