D3.js - 为什么mouseover和mouse out为每个子元素触发?

时间:2014-03-16 22:41:01

标签: javascript d3.js

我使用d3.js在圆圈中间生成带有文本徽标的svg圆圈。 这是svg的结果。

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

enter image description here

这是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事件(鼠标离开圆圈),然后再次发生鼠标悬停事件(鼠标进入文本元素),这不是可取的。

当鼠标触及&#34;&lt;&lt;&gt;的任何子元素时,似乎将调用动画回调。 g&gt;&#34;标签

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

2 个答案:

答案 0 :(得分:27)

另一种解决方案是使用mouseentermouseleave代替mouseovermouseout

mouseentermouseover类似,不同之处在于当指针(鼠标)从其中一个监听器(本例中为圆形)后代移动时未触发它。物理空间(在这种情况下是文本)到它自己的物理空间。

&#39; mouseleave&#39;

的相同推理

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

答案 1 :(得分:17)

通过将text设置为pointer-events,您可以阻止none元素接收鼠标事件(因此当您将鼠标悬停在鼠标上时会触发鼠标事件事件):

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
   })
相关问题