D3.js div在svg中阻止mouseover事件

时间:2015-05-07 16:23:52

标签: d3.js

如果我使用d3.js创建一个简单的散点图,我可以通过将'hey'打印到控制台上来记录圆形元素上的mouseover事件:

http://jsfiddle.net/pkerpedjiev/opmhaz0n/

<!DOCTYPE html>
<meta charset="utf-8">
<div class="chart" style="position: aboslute; left: 0px: top: 0px; width: 300px; height: 200px;" ></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
    var xVals = [4, 8, 15, 16, 23, 42,72];
    var yVals = [13, 49, 34, 2, 22, 23, 44];

    var data = xVals.map(function(d,i) { return [d, yVals[i]]; });

    var width=300;
    var height=200;

    console.log('data:', data);

    /*
    var div = d3.select(".chart").append("div")
    .style("position", "absolute")
    .style("width", width + "px")
    .style("height", height + "px")
    .style("left", 0 + "px")
    .style("top", 0  + "px")
    .style("opacity", 0.2);
    */ 

    var svg = d3.select(".chart")
    .append("svg")

    svg.selectAll('circle')
    .data(data)
    .enter()
    .append("circle")
    .attr('cx', function(d) { return d[0]; })
    .attr('cy', function(d) { return d[1]; })
    .attr('r', 4)
    .attr('fill', 'black')
    .on('mouseover', function(d) { console.log('hey'); });

</script>

但是,如果我在svg后添加div,则mouseover事件不会被记录:

http://jsfiddle.net/pkerpedjiev/Lxgbycr8/1/

<!DOCTYPE html>
<meta charset="utf-8">
<div class="chart" style="position: aboslute; left: 0px: top: 0px; width: 300px; height: 200px;" ></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
    var xVals = [4, 8, 15, 16, 23, 42,72];
    var yVals = [13, 49, 34, 2, 22, 23, 44];

    var data = xVals.map(function(d,i) { return [d, yVals[i]]; });

    var width=300;
    var height=200;

    console.log('data:', data);

    var div = d3.select(".chart").append("div")
    .style("position", "absolute")
    .style("width", width + "px")
    .style("height", height + "px")
    .style("left", 0 + "px")
    .style("top", 0  + "px")
    .style("opacity", 0.2);

    var svg = d3.select(".chart")
    .append("svg")

    svg.selectAll('circle')
    .data(data)
    .enter()
    .append("circle")
    .attr('cx', function(d) { return d[0]; })
    .attr('cy', function(d) { return d[1]; })
    .attr('r', 4)
    .attr('fill', 'black')
    .on('mouseover', function(d) { console.log('hey'); });

</script>

当svg后面的背景中有div时,有没有办法注册'mouseover'事件?

1 个答案:

答案 0 :(得分:1)

元素的定位会干扰您在此处对鼠标事件的期望,特别是您需要为SVG设置positionabsolute以使其出现在div

如果你想让SVG赶上&#34;赶上&#34;仅针对特定元素的事件,在SVG上设置pointer-eventsnone,在要接收事件的元素上设置all