D3。如何使用函数使用.attr方法设置多个属性

时间:2015-11-30 16:58:25

标签: d3.js svg

D3中我现在设置了一个rect的坐标:

.attr({
        x:function(d) { return histogram.renderX(d); },
        width:function(d) { return histogram.renderWidth(d); },

        y:function(d) { return histogram.renderY(d); },
        height:function(d, i) { return histogram.renderHeight(d, i); } 
}

这并没有给我配置rect的灵活性。我更喜欢按照以下方式做点什么:

.attr(coordinates(d, t));

coordinates看起来像这样:

    function coordinates(datum, index) {

        var coords = {};

        coords[      'x' ] = function(datum) { return histogram.renderX(datum); };
        coords[  'width' ] = function(datum) { return histogram.renderWidth(datum); };

        coords[      'y' ] = function(datum) { return histogram.renderY(datum); };
        coords[ 'height' ] = function(datum) { return histogram.renderHeight(datum, index); };

        return coords;
    }

我设想的功能将设置x,y,width,height更有趣的功能。我不清楚这里使用的正确语法。有人可以为我澄清一下吗?

1 个答案:

答案 0 :(得分:1)

您可以使用.each

function keyDown(e) {

     var e = event || window.event;
     if (e.altKey && e.keyCode == 80) {
        e.preventDefault ? e.preventDefault() : (e.returnValue = false);
        e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
        e.keyCode = 0;
     }
}