RKu*_*mar 6 javascript css d3.js
当我开始使用 d3.js 时,我不禁注意到它的方法与 jQuery 非常相似。
我的问题是:
当我需要修改
style匹配元素属性的多个 CSS 属性时,是否有一种速记方法,例如 jQuery 或 ReactJS 提供,例如Run Code Online (Sandbox Code Playgroud).style({width:100, height:100, backgroundColor:'lightgreen'})`如果我需要申请
width:100px,height:100px并background-color:lightgreen到<div>。
当然,我可以将这些链接起来,但是以这种方式更改多个属性可能会变得乏味:
.style({width:100, height:100, backgroundColor:'lightgreen'})`
Run Code Online (Sandbox Code Playgroud)
d3
.select('#test')
.style('width','100px')
.style('height','100px')
.style('background-color','lightgreen')Run Code Online (Sandbox Code Playgroud)
或者我可以在一个类中组合多个所需的属性,并为该类分配一个.classed(),这也可能在需要动态属性时使 CSS 样式表过于复杂:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>Run Code Online (Sandbox Code Playgroud)
d3
.select('#test')
.classed('testclass', true)Run Code Online (Sandbox Code Playgroud)
.testclass {
height: 100px;
width: 100px;
background-color: lightgreen;
}Run Code Online (Sandbox Code Playgroud)
但这些都不是我感兴趣的技术。
该接受的答案是不正确的(“有一个在API参考中没有这样的语法”),则您可以使用多个样式d3-selection-multi。请注意,您必须使用该方法styles(),而不是style()。所以,在你的情况下,它将是:
.styles({width:100, height:100, 'background-color':'lightgreen'})
Run Code Online (Sandbox Code Playgroud)
这是带有该更改的代码段:
.styles({width:100, height:100, 'background-color':'lightgreen'})
Run Code Online (Sandbox Code Playgroud)
d3.select('#test')
.styles({
'width': '100px',
'height': '100px',
'background-color': 'lightgreen'
})Run Code Online (Sandbox Code Playgroud)
由于d3-selection-multi不是默认包的一部分,您必须单独引用它。
注意:我声称(在这个答案的初始版本中)没有嵌入的方法来解决OP的问题。并且,从 D3 v6.7.0 开始,您仍然无法将样式作为对象直接传递给
.style()方法
在撰写本文时,您有两个选择:
const style = {"width":"100px","height":"100px","background-color":"lightgreen"}
Object.entries(style).forEach(([prop,val]) => d3.select("#test").style(prop,val))Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>Run Code Online (Sandbox Code Playgroud)
为什么我不鼓励你做后者:
因此,您是应用 1 行解决方案,还是仅出于此目的向应用程序包中添加最多13kB的遗留代码 - 完全取决于您。