SVG:将鼠标移动到<image>元素会触发父级<g>元素的mouseout事件(d3.js)

4
我有一个包含<rect><image><g>元素。 <g> 元素有鼠标移开事件监听器。问题在于,当我将鼠标从<rect>移动到<image>(在同一个g内)时,会触发鼠标移开事件(随后是“mouseover”事件)。
这里是示例。(以及Jsfiddle)
var x = 120;

var g = d3.select("svg")
    .append("g")
    .on('mouseover', function() {
        d3.select(this).append("text").text("mouseover").attr('transform','translate(0,'+x+')');
        x+=20;
    })
    .on('mouseout', function() {
        d3.select(this).append("text").text("mouseout").attr('transform','translate(0,'+x+')');  
        x+=20;  
    })

g.append("rect")
    .attr('width', 100)
    .attr('height', 100)
    .style('fill', 'lightgreen')

g.append('image')
    .attr("width", 30)
    .attr("height", 30)
    .attr("x", 35)
    .attr("y", 35)
    .attr("xlink:href","https://www.gravatar.com/avatar/f70adb32032d39add2559c2609a90d03?s=128&d=identicon&r=PG")

如何防止触发mouseout事件?

尝试过悬停效果吗?会产生相同的效果吗? - user2587132
这个问题可能会有所帮助:https://dev59.com/p2Qn5IYBdhLWcg3wVF0w。 - Lars Kotthoff
2个回答

12

当您在父容器上使用mouseout和mouseover时,您会在鼠标移动到后代元素之间获得事件。如果您只想听到鼠标进入或离开父级容器的位置,请改用mouseentermouseleave


顺便提一下,3.0.6 版本中的 mouseenter 和 mouseleave 不起作用。需要升级到最新版本的 d3.js(暂时使用 3.2.7 版本)。谢谢! - eagor
mouseenter和mouseleave polyfills在3.1中被添加。请参阅发布说明获取完整历史记录。 - mbostock

-2

使用

onpointerleave

解决了问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接