当我迈出进入 d3.js 的第一步时,我不禁注意到它的方法与 jQuery 非常相似。
我的问题是:
When I need to modify multiple CSS properties of a
style
attribute of matching element is there a shorthand approach, like jQuery or ReactJS provide, like.style({width:100, height:100, backgroundColor:'lightgreen'})`
if I need to apply
width:100px
,height:100px
andbackground-color:lightgreen
to a<div>
.
当然,我可以将它们链接起来,但是以这种方式更改多个属性可能会变得乏味:
d3
.select('#test')
.style('width','100px')
.style('height','100px')
.style('background-color','lightgreen')
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>
或者我可以在一个类中组合多个所需的属性,并为该类分配
.classed()
,当需要动态属性时,这也可能会使 CSS 样式表过于复杂:d3
.select('#test')
.classed('testclass', true)
.testclass {
height: 100px;
width: 100px;
background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>
但这些不是我感兴趣的技术。
最佳答案
accepted answer不正确(“API 引用中没有记录这样的语法”),您可以使用 d3-selection-multi
设置多种样式.注意必须使用方法styles()
,而不是 style()
.因此,在您的情况下,它将是:
.styles({width:100, height:100, 'background-color':'lightgreen'})
这是您进行更改的代码段:
d3.select('#test')
.styles({
'width': '100px',
'height': '100px',
'background-color': 'lightgreen'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="test"></div>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
如
d3-selection-multi
不是默认捆绑包的一部分,您必须单独引用它。
关于javascript - 在 D3.js 中使用 .style() 方法应用多种样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59454162/