我开始这个概念时遇到了一些麻烦。我从一个看起来像这样的JSON文件生成这个数据
{
"nodes": [
{"container": "1", "x" : 0, "y" : 0, "height" : 100, "width" : 100, "sample": "sample1"},
{"container": "2", "x" : 200, "y" : 0, "height" : 100, "width" : 100, "sample": "sample5"},
{"container": "3", "x" : 400, "y" : 0, "height" : 100, "width" : 100, "sample": "sample4"}
]
"samples" : [
{"id" : "Sample 1"},
{"id" : "Sample 2"},
{"id" : "Sample 3"}
]
}
数据目前就像这样表示
左侧是从数据生成的容器元素,右侧是内部具有
守则
有一个辅助函数用作阴影来指示容器在拖动函数中的位置,它适用于容器但不适用于样本
拖动功能:
var drag = d3.behavior.drag().origin(Object);
function createHelper(x, y){
helper = grid.selectAll('.helper').data([{}]).enter().insert('div', ":first-child")
.attr('class', 'helper')
.style('left', function(d){d.x = x; return d.x + 'px'})
.style('top', function(d){d.y = y; return d.y + 'px'})
.style('width', function(d){d.width = wBlob; return d.width + 'px'})
.style('height', function(d){d.height = hBlob; return d.height + 'px'})
.style("background-color", "black")
.style("opacity", ".3")
.style("padding", "1.5em")
.style("position", "absolute");
}
drag.on('dragstart', function(d){
if (helper) helper.remove();
createHelper(d.x, d.y);
});
drag.on('dragend', function(d){
var hx = helper.datum().x;
var hy = helper.datum().y;
d.x = hx;
d.y = hy;
d3.select(this).transition().duration(100).style('left', d.x + 'px').style('top', d.y + 'px')
.each('end', function(){helper.remove();});
});
drag.on('drag', function(d,i){
var x = d3.event.x;
var y = d3.event.y;
d.x = x;
d.y = y;
var hx = Math.round((d.x)/100)*100;
var hy = Math.round((d.y)/100)*100;
helper.datum().x = hx;
helper.datum().y = hy;
d3.select(this).style('left', d.x + 'px').style('top', d.y + 'px');
helper.style('left', hx + 'px').style('top', hy + 'px');
});
和侧面生成的样本的功能
samples = sidebar
.selectAll("div")
.data(data.samples)
.enter()
.append("li")
.style("display", "inline-block")
.style("grid-column", "5")
.style("width", "100px")
.style("height", "40px")
.style("margin", "0 0 0 0")
.style("list-style", "none")
.style("text-align", "center")
.style("padding", ".5rem")
.style("border", "3px #7f7f7f solid")
.style("box-sizing", "border-box")
.style("font-family", ".8rem/1 arial, helvetica, sans-serif")
.text(function(d, i) {
return d.id;
})
.on('contextmenu', function () {
d3.event.preventDefault()
}).call(drag);
所以我是d3的初学者,本周在jQuery中学习了拖拽和拖放功能,这些功能实现起来并不算太糟糕,并且一直在寻找在d3中实现这一目标的有效方法。