您可以使用drag.behaviour 为元素添加拖动事件。
1) 创建一个函数来处理拖动事件(d3.event 类型):
function dragmove(d) {
d3.select(this)
.style("top", ((d3.event.sourceEvent.pageY) - this.offsetHeight/2)+"px")
.style("left", ((d3.event.sourceEvent.pageX) - this.offsetWidth/2)+"px")
}
2) 使用上述函数作为处理程序创建拖动行为:
var drag = d3.behavior.drag()
.on("drag", dragmove);
3) 在 d3 选择中使用 .call 将其绑定到一个元素或一组元素:
d3.select("body").append("div")
.attr("id", "draggable")
.text("Drag me bro!")
.call(drag)
试试看:http://jsfiddle.net/HvkgN/2/
这是同样的例子,adapted for an svg text element:
function dragmove(d) {
d3.select(this)
.attr("y", d3.event.y)
.attr("x", d3.event.x)
}
var drag = d3.behavior.drag()
.on("drag", dragmove);
d3.select("body").append("svg")
.attr("height", 300)
.attr("width", 300)
.append("text")
.attr("x", 150)
.attr("y", 150)
.attr("id", "draggable")
.text("Drag me bro!")
.call(drag)