简体   繁体   中英

D3.js append tspan to text element

I have a D3 bar chart. When I mouseover of one of the bars, text appears.

But I would like another line of text to also appear. For this I need to append a <tspan> element.

I have seen examples, but can't get <tspan> to append to the text element.

The Graph is here , and full code on github .

'text' is appended and 'tspan' is appended to that,

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

The JS function 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);
}

Try the following:

To append:

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

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

and then on the hanldeMouseOver:

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

I got it by appending tspan in the function,

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

There is no tspan elsewhere.

Working example here

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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