如何在D3 Js图表中点击另一个圆圈时用原始颜色改变圆圈的颜色

时间:2016-12-15 09:49:05

标签: d3.js

我有一个D3 JS图表,它为每个类绘制圆,每个圆的半径是该特定类中的NoOfStudents。

我添加了一个Click事件,它会将圆圈的颜色从“黑色”更改为“lightcoral”。

我想要的功能是,如果我点击第二个圆圈(点击第一个圆圈后),那么所有圆圈应该恢复原来的“黑色”颜色。

如何实现这一目标?谢谢!

//data
let data = [{ "noOfStudent": 40, "class": "Class 1" }, { "noOfStudent": 30, "class": "Class 2" }, { "noOfStudent": 20, "class": "Class 3" }];
// set the dimensions and margins of the graph
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// set the ranges
var x = d3.scalePoint().range([0, width]).padding(0.4);
var y = d3.scaleLinear().range([height, 0]);

var svg = d3.select("body").append("svg").attr("style", "outline: thin solid red;")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

// get and format the data
data.forEach(function (d) {
    d.noOfStudent = +d.noOfStudent;
});

// Scale the range of the data in the domains
x.domain(data.map(function (d) { return d.class; }));
y.domain([0, d3.max(data, function (d) { return d.noOfStudent; }) * 1.2]);

// append the rectangles for the bar chart
svg.selectAll(".bar")
    .data(data)
    .enter().append("circle")
    .attr("class", "bar")
    .attr("cx", function (d) { return x(d.class); })
    .attr("cy", function (d) { return y(d.noOfStudent); })
    .attr("r", function (d) { return d.noOfStudent; })
    .text(function (d) { return d.noOfStudent; })

    .on("click", function (d) {
        d3.select(this).attr('r', d.noOfStudent)
            .style("fill", "lightcoral")
    });

// add the x Axis
svg.append("g").attr("transform", "translate(0," + height + ")").call(d3.axisBottom(x));

// add the y Axis
svg.append("g").call(d3.axisLeft(y));

1 个答案:

答案 0 :(得分:1)

给圈子一个类以便以后选择它们:

.attr("class", "bar allCircles") //i didnt use 'bar' on purpose as you may have used it elsewhere

将点击功能分开,正如我在评论中提到的那样,将所有圆圈的颜色设为黑色,然后点击圈子的颜色:

circles.on("click", function (d) {
        d3.selectAll('.allCircles').style('fill','black'); //fill all circles black
        d3.select(this).style("fill", "lightcoral"); //then fill this circle lightcoral
    });
相关问题