3

我正在创建一个 d3 力有向图。我的要求是单击和双击一个节点。
单击时,我需要执行不同的任务,双击时,我需要执行其他一些任务。

这就是我的代码的样子:

var node = svg.append("g")
          .attr("class", "nodes")
          .selectAll("circle")
          .data(graph.nodes)
          .enter().append("circle")
          .attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; })
          .attr("r", 5)
          .on("click",function(d){ alert("node was single clicked"); })
          .on("dblclick",function(d){ alert("node was double clicked"); })

这里的问题是,即使我双击节点,也会调用单击函数。

click双击节点时如何防止调用函数。
换句话说,当单击节点时,click必须调用函数,当双击时,dblclick必须调用函数。

非常感谢任何可以帮助我解决这个问题的人。

4

1 回答 1

2

您可以使用 区分单击和双击setTimeout,查看演示:

var timeout = null;

d3.select('rect').on("click", function(d) {
    clearTimeout(timeout);
    
    timeout = setTimeout(function() {
      console.clear();
      console.log("node was single clicked", new Date());
    }, 300)
  })
  .on("dblclick", function(d) {
    clearTimeout(timeout);
    
    console.clear();
    console.log("node was double clicked", new Date());
  });
rect {
  fill: steelblue;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Open the console and click / double click on the rect:
<svg width="400" height="110">
  <rect width="100" height="100" />
</svg>

于 2018-03-19T08:24:49.250 回答