d3圈onclick事件未触发

Soo*_*ran 6 jquery svg d3.js

我从svg开始,我创建了以下标记.

<svg width="500" height="600" class="graph-container">
  <g>
    <rect x="150" y="190" height="50" width="200" rx="30" ry="30" nodeId="1" children="3" style="fill: none; stroke: rgb(68, 68, 68);"></rect>
    <text x="250" y="220" text-anchor="middle" fill="#444" style="font-size: 24px;">root</text>

  </g>

</svg>
Run Code Online (Sandbox Code Playgroud)

我通过d3js在较大的矩形中添加了一个小圆圈.

$( document ).ready(function() {

var node = d3.select('g');
var addchild = node.append("circle")
            .attr("cx",320)
            .attr("cy",210)
            .attr("r",10)
            .attr("class","addchild")
            .style("fill","none")
            .style("stroke","#444");

            addchild.on("click", function() {
                alert("on click");
            });; 

});
Run Code Online (Sandbox Code Playgroud)

但是click事件没有触发.

这是相同的jsfiddle.

Rob*_*son 9

默认情况下,您只能单击实际绘制的形状部分.由于填充形状为"无",因此不会对点击进行响应.中风但确实非常薄且很难点击.

如果您希望未绘制的圆圈内部响应点击,您可以将指针事件属性更改为可见,然后圆圈内部将响应点击.

$( document ).ready(function() {

var node = d3.select('g');
var addchild = node.append("circle")
			.attr("cx",320)
			.attr("cy",210)
			.attr("r",10)
			.attr("class","addchild")
			.style("fill","none")
      .style("pointer-events","visible")
			.style("stroke","#444");
			
			addchild.on("click", function() {
				alert("on click");
			});; 

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="600" class="graph-container">
  <g>
    <rect x="150" y="190" height="50" width="200" rx="30" ry="30" nodeId="1" children="3" style="fill: none; stroke: rgb(68, 68, 68);"></rect>
    <text x="250" y="220" text-anchor="middle" fill="#444" style="font-size: 24px;">root</text>

  </g>

</svg>
Run Code Online (Sandbox Code Playgroud)

  • @SoorajChandran你当然可以,但如果你想要的只是响应点击事件,那将改变所绘制的内容并且效率不高. (2认同)