【问题标题】:Text element causing Rect element to recall mouseover event导致 Rect 元素调用 mouseover 事件的文本元素
【发布时间】:2015-02-28 01:16:09
【问题描述】:

我有一个包含文本的框,当用户用鼠标进入该框时,我会播放一个音调(使用 mouseover 事件)。这是使用 Rect 和 Text 元素完成的,它们是兄弟元素,都是 svg 元素的子元素(我使用的是 d3)。鼠标悬停事件附加到 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");

【问题讨论】:

    标签: javascript html d3.js


    【解决方案1】:

    您可以使用事件的 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

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

    编辑

    另一个选项是使用一个标志来确保声音不会在鼠标悬停时执行,除非是最初或移出矩形之后。 http://jsfiddle.net/nhx0o33t/2/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多