【问题标题】:D3.js append tspan to text elementD3.js 将 tspan 附加到文本元素
【发布时间】:2017-07-02 02:19:13
【问题描述】:

我有一个 D3 条形图。当我将鼠标悬停在其中一个栏上时,会出现文本。

但我希望另一行文本也出现。为此,我需要附加一个 元素。

我看过示例,但无法将 附加到文本元素。

图表是here,完整代码在github

'text' 被追加,'tspan' 被追加,

  g.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .style("fill", function(d) {
            return colorScale(d.intensity);
        })
        .attr("class", "bar")
        .attr("x", function(d) {
            return x(d.date);
        })
        .attr("y", function(d) {
            return y(d.distance);
        })
        // .attr("width", x.bandwidth())
        .attr("width", function(d) {
            return dur(d.duration);
        })
        // .attr("width", 6)
        .attr("height", function(d) {
            return height - y(d.distance);
        })
        .on("mouseover", handleMouseOver)
        .on("mouseout", handleMouseOut);

    t = g.append('text')
        .attr('x', 9)
        .attr('dy', '.35em');

    ts = g.append('tspan')
        .attr('x', 9)
        .attr('dy', '.35em');

JS函数handleMouseOver

  function handleMouseOver(d) {
    d3.select(this)
        .style("fill", "lightBlue")
    g.select('text')
        .attr("x", x(d.date) + dur(d.duration + 5))
        .attr("y", y(d.distance) + 10)
        .text(d.distance + "m");
    ts.text("blah")
        .attr("x", x(d.date) + dur(d.duration + 5))
        .attr("y", y(d.distance) + 30);
}

【问题讨论】:

  • 在网上没有看到太多关于如何使用 D3.JS 在<text> 中嵌套<tspan> 元素,但我自己澄清了。 [看这个问题](如何跳出D3JS中的嵌套selectAll?)。

标签: javascript d3.js append onmouseover tspan


【解决方案1】:

尝试以下方法:

追加:

t = g.append('text')
        .attr('x', 9)
        .attr('dy', '.35em');

ts = g.append('tspan')
        .attr('x', 9)
        .attr('dy', '.35em');

然后在 hanldeMouseOver 上:

ts.text("blah")
    .attr("x", ...)
    .attr("y", ...);

【讨论】:

  • 我进行了这些更改并更新了问题以反映这一点。但不幸的是,图表是相同的。谢谢
  • 鼠标悬停函数中ts = ...之前的行尾应该是分号吗?
【解决方案2】:

我是通过在函数中附加 tspan 得到的,

function handleMouseOver(d) {
    d3.select(this)
        .style("fill", "lightBlue")
    g.select('text')
        .attr("x", x(d.date) + dur(d.duration + 5))
        .attr("y", y(d.distance) + 10)
        .text(d.distance + "m")
        .append('tspan')
        .text(d.number)
        .attr("x", x(d.date) + dur(d.duration + 5))
        .attr("y", y(d.distance) + 30)
        .append('tspan')
        .text(d.date)
        .attr("x", x(d.date) + dur(d.duration + 5))
        .attr("y", y(d.distance) + 50);
}

其他地方没有tspan。

工作示例here

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多