d3js中的子节点的样式

时间:2014-02-04 11:59:38

标签: svg d3.js

我试图制作一个包含节点和链接的简单图表。我有" g"包含圆圈及其文本的元素,以及自己的链接。例如,我有一个关于鼠标悬停事件的代码:

//check if circle is connected to current "viewed" (mouseover-ed) 
//circle via a link referenced by "that" and paint it green if so
circles.filter(function() {
         return d3.select(this).attr("index") == d3.select(that).attr("src");
         }).attr("viewed",1).style("stroke", "green");
                     });

由于节点是“g'元素容器,我不确定调用.style会做什么,但令我惊讶的是它确实改变了颜色 - 但仅限于文本!

有没有办法让它改变圆圈的笔触样式?

声明代码:

var circles = svg.append("g")
    .attr("class","nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter()
    .append("g")
    .attr("transform",function(d,i){d.x = getX(i);d.y=getY(i);return "translate(" + d.x + "," + d.y + ")";})
    .attr("name", function(d){return d.name;})
    .attr("viewed",  0)
    .attr("focused", 0)
    .attr("index", function(d, i) {return i;});


circles.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
   .attr("r", node_radius_wo_pad)
    .on("mouseover", function(){...};


circles.append("text")
        .attr("text-anchor","middle")
        .text(function(d){return d.name});

1 个答案:

答案 0 :(得分:1)

这样做的原因是你没有为文本显式声明笔触颜色,因此它继承了你为父g元素设置的颜色。要使这项工作适用于圈子,您必须明确选择它们:

var toChange = circles.filter(function() {
       return d3.select(this).attr("index") == d3.select(that).attr("src");
     });
toChange.attr("viewed", 1);
toChange.selectAll("circle").style("stroke", "green");
toChange.selectAll("text").style("stroke", "green");