导致Rect元素调用mouseover事件的文本元素

时间:2015-02-28 01:16:10

标签: javascript html d3.js

我有一个包含文字的框,当用户用鼠标进入框时,我会播放一个音(使用鼠标悬停事件)。这是使用Rect和Text元素完成的,它们是兄弟姐妹,是svg元素的两个子元素(我使用的是d3)。 mouseover事件附加到Rect。

问题是,当鼠标进入Rect时,它会按预期播放音调,但当它们将鼠标悬停在Rect内的Text上,然后退出Text并返回到Rect时,Rect中的mouseover事件是又叫了一遍。我想完全忽略鼠标输入文本,以便只触发一次Rect事件,而不是再次触发,直到鼠标实际离开矩形并再次重新输入。这是一些代码:

svg.append("rect")
          .attr('width', boxSize)
          .attr('height', boxSize)
          .attr('x', x - boxSize / 2)
          .attr('y', y - boxSize / 2)
          .on("mouseover", function() {
                  var freq = GetFrequency(innerRowNum, innerRowIndex);
                  var oscillator = startOscillator(freq, true);
           });
svg.append("text")
          .attr("x", x)
          .attr("y", y)
          .attr("dy", ".35em")
          .attr("text-anchor", "middle")
          .style("font", "300 " + (boxSize * 0.6) + font)
          .style("fill", "white")
          .style("pointer-events", "none")
          .text("Text");

1 个答案:

答案 0 :(得分:2)

您可以使用事件的fromElement属性来检查鼠标以前是否在文本上:

svg.append("rect")
//...
.addEventListener("mouseover",function(evt){
   if( evt.fromElement.id != "text-id" ){
      var freq = GetFrequency(innerRowNum, innerRowIndex);
      var oscillator = startOscillator(freq, true);
   }
});

但Firefox似乎不支持fromElement。见http://help.dottoro.com/ljjqfjbs.php

您还可以在父级上定义监听鼠标悬停并检查鼠标是否在矩形内。

修改

另一种选择是使用一个标志来确保除了最初或移出rect之后鼠标悬停时不执行声音。 http://jsfiddle.net/nhx0o33t/2/