如何更改SVGCircleElement对象的样式?

时间:2015-10-29 14:33:03

标签: css d3.js svg

在我的散点图中,我想在鼠标悬停时更改圆形的样式(不透明度/颜色),也可以在共享相同className的所有其他圆上更改。

groupList[i].style("opacity", .6);似乎不是正确的方法。

var mouseOver = function() { 
    var circle = d3.select(this);

    var highlitedGroup = this.className.baseVal;

    var groupList = document.getElementsByClassName(highlitedGroup);

    // The styling for the circle which mouse is over it.     
    circle.transition()
        .duration(800).style("opacity", 1)
        .attr("r", 16).ease("elastic");

    // For the all other circles which have the same className do this styling  
    for (var i=0; i<groupList.length; i++) {
               // List of SVGCircleElement objects  
                groupList[i].style("opacity", .6); //??
        }     
}

1 个答案:

答案 0 :(得分:1)

因为您已经在使用D3.js,所以我建议您尽可能在代码中坚持使用它。在这种情况下,你的功能归结为基本上两个陈述,其中第一个操纵主圆圈,而第二个将处理具有相同类别的所有圆圈。

var mouseOver = function() {

  // The styling for the circle which mouse is over it.     
  d3.select(this).transition()
    .duration(800).style("opacity", 1)
    .attr("r", 16).ease("elastic");

  // For the all other circles which have the same className do this styling  
  d3.selectAll("." + this.className)
    .style("opacity", .6);

}

请注意,只有在主圈中只分配了一个班级时才能使用此功能。如果为此元素分配了多个类,this.className将包含一个以空格分隔的类名列表,从而破坏了选择。