如何使用d3.js拖动行为拖动svg组? [英] How to drag an svg group using d3.js drag behavior?
问题描述
我使用 D3js drag 。单个元素被拖动完全精细。但我想拖动一组元素。它可以做到。以下是我的 Js小费链接:
I am using D3js drag. single element is get dragged perfectly fine. but i want to drag a group of elements.How it can be done. Here is what is on my Js Fiddle link:
function onDragDrop(dragHandler, dropHandler) {
var drag = d3.behavior.drag();
drag.on("drag", dragHandler)
.on("dragend", dropHandler);
return drag;
}
var g = d3.select("body").select("svg").append("g")
.data([{ x: 50, y: 50 }]);
g.append("rect")
.attr("width", 40)
.attr("height", 40)
.attr("stroke", "red")
.attr("fill","transparent")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.call(onDragDrop(dragmove, dropHandler));
g.append("text")
.text("Any Text")
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y; })
.call(onDragDrop(dragmove, dropHandler));
function dropHandler(d) {
// alert('dropped');
}
function dragmove(d) {
d3.select(this)
.attr("x", d.x = d3.event.x)
.attr("y", d.y = d3.event.y);
}
我想同时拖动rect和text。这是我尝试了,但没有运气。
I want to drag both rect and text simultaneously. Here is what I tried, but no luck. I think am missing something simple.
推荐答案
首先,< g>元素不关心 x
和 y
属性(如:它们被忽略)。您可以使用 transform =translate(x,y)
。
First off, the <g> element doesn't care about x
and y
attributes (as in: they're just ignored). You can use transform="translate(x,y)"
instead.
你在dragmove处理程序中获得的元素实际上是< g>元素,而不是它的子元素。这是因为< g>元素本身没有实际的命中区域。他们的孩子做,而鼠标事件首先去孩子,然后泡沫到父母。您可以检查 evt.target
和 evt.currentTarget
以查看此操作。 target
是最初命中的元素, currentTarget
是当前正在处理事件的事件目标; g> element如果事件冒泡了)。
Second, you will need to check that the element you get in the dragmove handler actually is the <g> element, and not a child element of it. This is because <g> elements have no actual hit area themselves. Their children do though, and the mouse events first go to the children then bubble up to the parent. You can inspect evt.target
and evt.currentTarget
to see this in action. target
is the element that was hit originally, currentTarget
is the event target that is currently handling the event (e.g the <g> element if the event bubbled up).
这篇关于如何使用d3.js拖动行为拖动svg组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!