我想为文本元素添加背景颜色 . 我意识到我无法使用CSS样式设置背景颜色,因为这是SVG文本,所以我尝试追加矩形但成功:
let g = svg.selectAll("g")
.data(["1 year", "2 years", "3 years", "4 years", "5 years"])
.enter()
.append("g")
.attr("transform", "translate(" + (markerCirclesScale(name) + 330) + "," + (fullSVGHeight / 2 - 60) + ")" );
g.append("text")
.attr("text-anchor", "middle")
.style("font-size", 10)
.style("fill", "black")
.attr("y", function(d,i){
return i * (-65);
})
.text(function(d){
return d;
})
g.append("rect")
.attr("x", function(d){ return this.parentNode.getBBox().x - 10;})
.attr("y", function(d, i){ return this.parentNode.getBBox().y })
.attr("width", function(d){ return this.parentNode.getBBox().width + 20;})
.attr("height", function(d) {return 40;})
.style("fill", "#80d6c7");
但是我意识到改变DOM中的顺序就是伎俩,为什么这不能通过改变代码顺序来工作?!
1 回答
您正在插入
<text>
元素,然后用<rect>
元素覆盖它们 .如果您只是颠倒添加这些元素的顺序,则会显示文本 .
这是我的codepen