我想显示一些数据的图例(标题?)。 对于图例的每一部分,我将一个 rect 和一个 p 附加到父分区。 问题是 rect 没有出现。
这是我的代码:
var groups = {{ groups|safe }};
groups.forEach(function(group, i) {
var div = d3.select("#collapse-legend");
div.append("rect")
.attr("width", 17)
.attr("height", 17)
.style("fill-opacity", 1)
.style("fill", function (d) { return c(i); });
div.append("p").text(group)
});
现在,当我检查我的网页内容时,我得到了 rect 和 p,但是 rect:
- 没有出现
- 似乎宽度为 0(用 firefox 显示它的区域)
我的代码有什么错误吗?有没有更好的方法来实现这一目标?我是 javascript 和 d3.js 的新手,所以请放纵一下 ^^
更新
这就是我的结局。
HTML:
<div ...>
<svg id="legend-svg"></svg>
</div>
JavaScript:
// set height of svg
d3.select("#legend-svg").attr("height", 18*(groups.length+1));
// for each group, append rect then text
groups.forEach(function(group, i) {
d3.select("#legend-svg").append("rect")
.attr("y", i*20)
.attr("width", 18)
.attr("height", 18)
.style("fill-opacity", 1)
.style("fill", function (d) { return c(i); });
d3.select("#legend-svg").append("text")
.attr("x", 25)
.attr("y", i*20+15)
.text(group);
});
最佳答案
SVG 元素,如 <rect>
不能是 html <div>
的直接子代元素。您必须将它们放在 <svg>
中容器元素。
关于javascript - d3 rect 没有显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28698696/