d3如何在文本后面的对象上触发事件

yon*_*nan 6 javascript svg mouseevent d3.js

我画了一个recttextsvg.

为了展示text,我rect先渲染.

我添加mouse click eventrect

当我单击文本时,似乎没有选择rect,因为rect在文本后面,因此文本被选中.

当鼠标点击内部时,我需要选择触发事件rect.

我应该怎么做?

谢谢!

小提琴

您可以看到,当您单击文本时,不会单击rect.

var data = ["TEXT SAMPLE TEXT SAMPLE TEXT SAMPLE"];

var svg = d3.select("svg");
var bar = svg.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(100,100)"; });

bar.append("rect")
    .attr("width", 200)
    .attr("height", 50)
    .style("fill", "#f00")
    .on("click", function (d) {
                            alert("text");
                    });
bar.append("text")
    .attr("x", 10)
    .attr("y", 25)
    .attr("dy", "-.35em")
    .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

Pet*_*uzs 9

您可以将样式附加到文本以忽略鼠标事件.这是一个例子:

样式:

.bar-text {
    pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)

修改后的代码

bar.append("text")
    .attr("x", 10)
    .attr("y", 25)
    .attr("class", "bar-text") // add class
    .attr("dy", "-.35em")
    .text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)