我将在svg元素上设置各种css样式,并且认为我可以做类似的事情
d3.selectAll(".whatever")
.style(function(d) { return {"color":getColor(d), "background":getBackground(d)}});
现在,这不起作用,但我想知道我是否可以做类似于集中设置整体样式属性而不是单独设置样式属性。
注意:正如Ray建议的那样,你可以这样做(我假设你已经将数据附加到节点上):
d3.selectAll(".whatever")
.attr("style",function(d) {
return cssStyleStringYouWantToUse(d);
});
答案 0 :(得分:6)
仅适用于D3 v3 :
引用the documentation:
如果要一次设置多个样式属性,请使用如下对象文字:
selection.style({' stroke':' black',' stroke-width':2})
虽然功能不可行,但在你的情况下,你仍然需要使用" long form"。
答案 1 :(得分:3)
您可以为样式文字中的每个样式名称指定单独的函数,如下所示:
d3.selectAll(".whatever").style({
color: function(d) { return getColor(d); },
background: function(d) { return getBackground(d); }
});
答案 2 :(得分:1)
在d3中应用多个CSS(静态或动态)的最简单方法是根据需要设置style
多次。例如:
d3.selectAll('whatever')
.style('color', 'green')
.style('height', (d) => d + 'px');