【问题标题】:D3.js - why mouseover and mouse out fired for each child elements?D3.js - 为什么为每个子元素触发 mouseover 和 mouse out?
【发布时间】:2014-03-16 22:41:01
【问题描述】:

我使用 d3.js 生成一个 svg 圆圈,圆圈中间有一个文本徽标。 这是 svg 结果。

<g id="main">
  <circle r="114" fill="#F0E8D0"></circle>
  <text text-anchor="middle">The movie title</text>
</g>

这里是 d3.js

var circles = [{r: innerRadius}];
svg.append("g").attr("id","main");


svg.select("#main").selectAll("circle")
.data(circles).enter()
.append("circle")
.attr("r",function(d){return d.r})
.attr("fill","#F0E8D0");

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

我还想在鼠标悬停离开圆圈时触发一些动画。

svg.select("#main")
.on("mouseover",function(){
  //code for transition
}).on("mouseout",function(){
  //code for transition
})

所以问题是: 当鼠标移入圆圈时,动画会按预期触发,但是,当鼠标触摸文本元素时,会触发 mouseout 事件(鼠标离开圆圈),然后再次触发 mouseover 事件(鼠标进入文本元素),这不是可取的。

似乎当鼠标触摸到“”标签的任何子元素时,动画回调会被调用。

我不希望鼠标触摸文本元素时发生任何动画。我该怎么做?

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    另一种解决方案是使用mouseentermouseleave 而不是mouseovermouseout

    mouseentermouseover 类似,只是当指针(鼠标)从侦听器(本例中为圆圈)的后代的物理空间(本例中为文本)之一移动到其自己的物理空间时不会触发空间。

    'mouseleave' 的理由相同

    来源:https://developer.mozilla.org/en-US/docs/Web/Events/mouseenterhttps://developer.mozilla.org/en-US/docs/Web/Events/mouseleave

    【讨论】:

    • 这是正确且首选的答案,因为对于悬停在圆圈内的每个元素,事件不会触发多次。
    【解决方案2】:

    您可以通过将pointer-events 设置为none 来阻止text 元素接收鼠标事件(因此当您将鼠标移到它上面时触发mouseout 事件):

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

    您可能还想在 circle 而不是 g 元素上设置事件:

    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
       })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-08
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多