.append()方法是将D3对象添加到HTML中的唯一方式吗?
我正在使用append()方法将一个treemap添加到我的HTML文件的body中,但我想将treemap添加到一个元素的内部。问题在于,append()方法是将元素添加在当前元素之后,而不是在当前元素之内。我想要将treemap的大小调整为浏览器初始高度和宽度的100%(像这样)。添加CSS似乎是最直接的方法。
我尝试通过将treemap附加到一个div内部的div来“欺骗”D3.js,但这没有起作用。
也许我问错了问题,我应该在d3.js脚本内调整treemap的大小?我已经尝试过更改bl.ock.org提供的默认样式,但我还没有使treemap扩展到全屏。
这里是我认为初始化treemap的代码。
var margin = {top: 40, right: 10, bottom: 10, left: 10},
width = 1000 - margin.left - margin.right,
height = 650 - margin.top - margin.bottom;
var color = d3.scale.category20c();
var treemap = d3.layout.treemap()
.size([width, height])
.sticky(false)
.value(function(d) { return d.size; });
var div = d3.select("body").append("div")
.style("position", "relative")
.style("width", (width + margin.left + margin.right) + "px")
.style("height", (height + margin.top + margin.bottom) + "px")
.style("left", margin.left + "px")
.style("top", margin.top + "px");
以下是更改节点大小以适应 JavaScript 值的代码。
var root;
socket.on('update', function(stream) {
console.log('tweets')
div.datum(root).selectAll(".node").remove();
root = stream.masterlist;
var node = div.datum(root).selectAll(".node")
.data(treemap.nodes)
.enter().append("div")
.attr("class", "node")
.call(position)
.style("background", function(d) { return d.children ? color(d.name) : null; })
.text(function(d) { return d.children ? null : d.name; });
});
});
function position() {
this.style("left", function(d) { return d.x + "px"; })
.style("top", function(d) { return d.y + "px"; })
.style("width", function(d) { return Math.max(0, d.dx - 1) + "px"; })
.style("height", function(d) { return Math.max(0, d.dy - 1) + "px"; });
}
.insert(element[, before])
这个方法可以微调D3添加元素的位置。 - musically_ut