简体   繁体   English

d3 SVG文本元素background-color与getBBox()的顺序错误

[英]d3 SVG text element background-color with getBBox() wrong order

I would like to add a background color to the text elements. 我想为文本元素添加背景色。 I realise I cannot set a background color using CSS styles because this is SVG text, so I tried to append rectangles but to success: 我意识到我无法使用CSS样式设置背景颜色,因为这是SVG文本,因此我尝试附加矩形但成功了:

Codepen Codepen

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");

However I realised changing order in DOM doest the trick, why this doesn't work by changing code order?! 但是我意识到改变DOM中的顺序并不能解决问题,为什么改变代码顺序不起作用?

在此处输入图片说明

You are inserting the <text> elements, and then covering them up with <rect> elements. 您要插入<text>元素,然后用<rect>元素覆盖它们。

If you simply reverse the order in which you are appending these elements, then text will show up. 如果您只是简单地颠倒了添加这些元素的顺序,那么将会显示文本。

Here is my codepen 这是我的codepen

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM