我正在尝试创建一个图例,显示颜色 block 、与该颜色对应的名称以及用于更改颜色的下拉列表。这是我的代码:
function create_legend(){
var legend = legendSVG.selectAll("g.legend")
.data(ext_color_domain)
.enter().append("g")
.attr("class", "legend");
var ls_w = 20, ls_h = 20;
//create color blocks
legend.append("rect")
.attr("x", 20)
.attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
.attr("width", ls_w)
.attr("height", ls_h)
.style("fill", function(d, i) { return color_scale[i]; })
.style("opacity", 0.8);
//create text
legend.append("text")
.attr("x", 50)
.attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
.text(function(d, i){ return segment_map[i]; });
//create dropdown for colors
legend.append("div")
.append("select")
.attr("x", 80)
.attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
.selectAll("option")
.data(color_names)
.enter().append("option")
.attr("value", function (d) { return d; })
.text(function (d) { return d; });
}
颜色和文本出现,但下拉元素不出现。
更新:好的,我尝试执行以下操作,但它给了我错误“Uncaught SyntaxError:意外的 token ”
'//create dropdown for colors
legend.append("foreignObject")
.attr("class", ".dropdown")
.append("div")
.append("select")
.attr("x", 80)
.attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
.selectAll("option")
.data(color_names)
.enter().append("option")
.attr("value", function (d) { return d; })
.text(function (d) { return d; });'
最佳答案
在 SVG 中,html 元素只能是foreignObject 元素的子元素,而foreignObject 元素不能是text 元素的子元素。不过,foreignObject 元素可以是文本元素的同级元素,因此您的 DOM 需要如下所示。
g
|- rect
|- text
|- foreignObject
|- div
关于javascript - 附加到 D3 中时元素不出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36228337/