代码之家  ›  专栏  ›  技术社区  ›  Jim

在文本后面添加大小正确的矩形

  •  1
  • Jim  · 技术社区  · 6 年前

    我目前正在向SVG追加文本节点,如下所示:

    var node = svg.selectAll(...);
    node.append("text")
        .attr("dy", 10)
        .attr("dx", 4)
        .text(function (d) { return d["name"]; });
    

    目前大约有10个节点,每个节点都有一个名称。

    我想在每个文本节点下面添加一个矩形,使用正确的宽度,我已经尝试过:

    node.select<SVGTSpanElement>("text")
        .each(function(x, i) {
            console.log(this.getComputedTextLength());
            node.append("rect")
                .attr("fill", "#cccccc05")
                .attr("width", this.getComputedTextLength())
                .attr("height", 20)
        });
    

    我的问题是(很明显)我正在创建10个矩形 节点,不是每个节点一个。

    如何包括文本宽度的计算,并为每个文本元素添加一个矩形?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gerardo Furtado    6 年前

    在不重构过多代码的情况下,只需更改 哪里 你在附加矩形。在这种情况下,文本本身的父节点:

    node.select<SVGTSpanElement>("text")
        .each(function(x, i) {
            console.log(this.getComputedTextLength());
            d3.select(this.parentNode).append("rect")
                .attr("fill", "#cccccc05")
                .attr("width", this.getComputedTextLength())
                .attr("height", 20)
        });
    

    然而,最惯用的方法是 each() 对于 node 选择,不用于选择其中的文本。然后,你得到每个的文本长度 结点 元素,类似于:

    node.each(function(x, i) {
        d3.select(this).append("rect")
            .attr("fill", "#cccccc05")
            .attr("width", d3.select(this).select("text").node().getComputedTextLength())
            .attr("height", 20)
        });