javascript - d3 SVG 文本元素背景颜色与 getBBox() 顺序错误

标签 javascript d3.js svg

我想为文本元素添加背景颜色。我意识到我无法使用 CSS 样式设置背景颜色,因为这是 SVG 文本,所以我尝试附加矩形但成功了:

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

但是我意识到更改 DOM 中的顺序并不能解决问题,为什么通过更改代码顺序不起作用?!

enter image description here

最佳答案

您正在插入<text>元素,然后用 <rect> 覆盖它们元素。

如果您只是颠倒附加这些元素的顺序,则会显示文本。

这是我的 codepen

关于javascript - d3 SVG 文本元素背景颜色与 getBBox() 顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53690896/

相关文章:

javascript - Meteor "--mobile-settings"被服务器值覆盖了吗?

javascript - Angular 和 D3.js : Why is element[0] undefined?

javascript - 无法将 mousedown 事件附加到嵌入元素

javascript - JQuery:使用元素的html()(innerHTML)作为canvas的drawSvg方法的参数

javascript - 是否可以在 svg 元素中将 anchor 标记包裹在 circle 元素周围?

javascript - 使用javascript从数组中的特定对象获取x和y坐标

javascript - 使用客户端 Javascript 从 Node 的 readStream 保存图像

javascript - scrolltop 在 centos 上不起作用

javascript - 如何做描边不透明度 :0 with d3

javascript - d3js 给出类型错误 "d is undefined"