简体   繁体   English

如何在d3.js强制有向图中检测元素拖动

[英]how to detect element drag in d3.js force directed graph

I have a force directed graph in d3.js (Brilliant: big kudos to MB and all involved!). 我在d3.js中有一个力导向图(出色:对MB以及所有相关的东西都赞不绝口!)。 I'd like to somehow be able to detect, and return the index of any node that's currently being dragged. 我希望能够以某种方式检测并返回当前正在拖动的任何节点的索引。

I know that I can redefine d3.behavior.drag() to attach a callback to the drag event, but I want all the behavior of the native force.drag and it seems clumsy to reduplicate it all just to add this one little bit. 我知道我可以重新定义d3.behavior.drag()来将回调函数附加到拖动事件,但是我想要本机force.drag的所有行为,并且将所有这些都重新复制起来似乎很笨拙,只是添加了一点。 In my inexperience, perhaps I'm overlooking some straightforward way to do this? 以我的经验,也许我忽略了一些简单的方法来做到这一点?


hmm, yes, I should be more explicit. 嗯,是的,我应该更加明确。 This is what I tried: I've used the example here as my model, modifying it to suit my purposes, and learning d3.js as I go. 这就是我尝试的方法:我在这里使用了示例作为模型,对其进行了修改以适合我的目的,并在学习过程中学习了d3.js。 I defined the nodes thus: 我这样定义了节点:

var circle = svg.append("svg:g").selectAll("circle")
    .data(force.nodes())
  .enter().append("svg:circle")
    .attr("class", "node")
    .attr("r", 6)
    .on("click", clicked)
    .on("dblclick", dblclick)
    .on("contextmenu", cmdclick)
    .on("drag", draghandler)
    .call(force.drag);

function draghandler(d){
    console.log(d);
    console.log(this);
}

My event handlers for click , dblclick , and contextmenu , work exactly as I expect; 我的clickdblclickcontextmenu事件处理程序完全按照我的期望工作; however, when I try to add an event handler for drag , it never executes. 但是,当我尝试为drag添加事件处理程序时,它永远不会执行。 I imagined that it was failing because I was using it wrong, or in the wrong place, or that because the behavior is governed by force.drag , I would have to redefine that to add the additional behavior I wanted. 我以为它会失败,因为我在错误的地方或错误的地方使用了它,或者因为行为是由force.drag ,所以我必须重新定义它以添加我想要的其他行为。

The drag event is not fired by circle , it's fired by the the drag behavior ( source ), calling force.drag will return that behavior and you can set a listener there: drag事件不是由circle触发的,而是由drag行为( source )触发的,调用force.drag将返回该行为,您可以在此处设置侦听器:

force.drag()
  .on("dragstart", function () {
    console.log(arguments);
  })

Demo , see the console's output 演示 ,查看控制台的输出

Update: 更新:

I forked the example link you posted which doesn't use d3.json and it's working fine: demo 我分叉了您发布的示例链接,该示例链接不使用d3.json ,并且运行良好: demo

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

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