在链接 d3 force 布局中添加和删除类

fer*_*der 1 javascript svg d3.js

如何在力布局的链接中添加和删除类。考虑一下d.source.x == d.target.x我是否必须添加类,否则我必须从链接中删除该类。

path.attr("d", function(d) {
    var x1 = d.source.x,
        y1 = d.source.y,
        x2 = d.target.x,
        y2 = d.target.y,
        dx = Math.abs(x2 - x1),
        dy = Math.abs(y2 - y1),
        dr = dx * dx + dy * dy;

    var rotation = 0;
    if (x1 === x2) {

        var dr = Math.sqrt(dx * dx + dy * dy) / 1.8; // note that this is always equal to Math.abs(dy)
        var sweep = 1;
        if (y1 > y2) {
            sweep = 0;

        }

        return "M" +
            d.source.x + "," + d.source.y +
            "A" + dr + "," + dr +
            " 0, 0" + sweep + " " +
            d.target.x + "," + d.target.y;
    }



    return "M" +
        d.source.x + "," +
        d.source.y + "A" +
        dr + "," + dr + " 0 0,1 " +
        d.target.x + "," +
        d.target.y;
});
Run Code Online (Sandbox Code Playgroud)

Gil*_*sha 5

使用 d3 分类运算符。

if(d.source.x == d.target.x){
   d3.select(this).classed("your-class-name",true); //Adding class
} else{
   d3.select(this).classed("your-class-name",false); //Removing class
}
Run Code Online (Sandbox Code Playgroud)

或者干脆 d3.select(this).classed("your-class-name",d.source.x == d.target.x);

有关更多详细信息,请参阅jaketrent.com 上的D3 类操作