简体   繁体   English

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

[英]d3 How to trigger event on the object behind text

I draw A rect and text on svg.我在 svg 上绘制了一个recttext

In order to show text , I render rect first.为了显示text ,我先渲染rect

I add mouse click event to rect我将mouse click event添加到rect

when I click the text, it seems the rect is not selected, because rect is behind text, so text is selected frist.当我单击文本时,似乎没有选择 rect,因为 rect 在文本后面,所以首先选择了文本。

I need to select trigger the event when mouse click inside the rect .当鼠标在rect内单击时,我需要选择触发事件。

How should I do?我应该怎么做?

Thanks!谢谢!

Fiddle小提琴

You can see, when you mouse click on the text, the rect is not clicked.你可以看到,当你鼠标点击文本时,矩形没有被点击。

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; });

You can attach a style to the text to ignore mouse events.您可以将样式附加到文本以忽略鼠标事件。 Here is the example:这是示例:

Style:风格:

.bar-text {
    pointer-events: none;
}

Modified code:修改后的代码:

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

Attach the handler to the g element.将处理程序附加到g元素。 Complete demo here .在这里完成演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM