简体   繁体   中英

d3 create border around legend under <g>

I want a box surrounding each individual legend whenever there is a mouseover event. My legend is formed in a way like this:

var legend = svg.selectAll(".legend")
    .data(zColor.domain())
    .enter().append("g")
    .style("zIndex", 1)
    .attr("class", "legend")
    .attr("transform", function (d, i) {
        return "translate(0," + i * 22 + ")";
    });

legend.append("rect")
    .attr("x", xScale(d3.max(data, xValue)) * 1.05)
    .attr("y", -12)
    .attr("width", 18)
    .attr("height", 18)
    .attr("fill", zColor)
/*
-----------------------------------------------------------------------
I want this effect to happen on the entire <g>, not just on the <rect>.
-----------------------------------------------------------------------
    .on("mouseover", function () {
        d3.select(this).style("stroke-width", 2).style("stroke", "black");
    })
    .on("mouseout", function () {
        d3.select(this).style("stroke-width", 0);
    });
*/
legend.append("text")
    .attr("x", xScale(d3.max(data, xValue)) * 1.05 + 20)
    .attr("y", 0)
    .style("text-anchor", "start")
    .text(function (d) {
        return d;
    });

How can I do it at <g.legend> level? I have tried to surround a <div> around each one, but the entire legend disappeared.


[Update]

This is what I did to append a <div> under <g> and group <rect> and <text> together. However, the legend is not plotted in this case.

var legend = svg.selectAll(".legend")
    .data(zColor.domain())
    .enter().append("g")
    .style("zIndex", 1)
    .attr("class", "legend")
    .attr("transform", function (d, i) {
        return "translate(0," + i * 22 + ")";
    });
var legendDiv = legend.append("div").style("stroke-width", 2).style("stroke", "black");
legendDiv.append("rect")
    .attr("x", xScale(d3.max(data, xValue)) * 1.05)
    .attr("y", -12)
    .attr("width", 18)
    .attr("height", 18)
    .attr("fill", zColor);
legendDiv.append("text")
    .attr("x", xScale(d3.max(data, xValue)) * 1.05 + 20)
    .attr("y", 0)
    .style("text-anchor", "start")
    .text(function (d) {
        return d;
    });

When your code executes

legend.append("rect")

the result is the appended rectangle. (D3 is not like jQuery in this respect.)

Instead, you want

legend.on("mouseover", function() {/*...*/});     // ...

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