在D3.js中使用.style()方法应用多种样式 [英] Apply multiple styles with .style() method in D3.js

查看:76
本文介绍了在D3.js中使用.style()方法应用多种样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我迈入d3.js的第一步时,我不禁注意到自己的方法与jQuery非常相似.

As I'm making my first steps into d3.js I couldn't help myself noticing its approach is very similar to jQuery.

我的问题是:

当我需要修改 style 属性的多个CSS属性时匹配元素的存在是否有速记方法,例如jQuery或ReactJS提供的功能,例如

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'})` 

如果我需要应用 width:100px height:100px background-color:lightgreen 转换为< div> .

if I need to apply width:100px, height:100px and background-color:lightgreen to a <div>.

当然,我可以将它们链接起来,但是以这种方式更改多个属性可能会变得乏味:

Sure, I may chain those, but changing multiple properties this way may become tedious:

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样式表过于复杂:

Or I may combine multiple desired properties within a class and assign that class with a .classed(), which may also overcomplicate CSS stylesheet when dynamic properties are required:

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>

但是那些不是我感兴趣的技术.

But those are not techniques I'm interested in.

推荐答案

据我所知,如果您需要使用对象作为样式源,则可以尝试以下变通方法,尽管(基于 .forEach()遍历 Object.entries()):

If you need to use an object as a style source, you may try following workaround, though (based on .forEach() looping over Object.entries()):

const style = {"width":"100px","height":"100px","background-color":"lightgreen"}

Object.entries(style).forEach(([prop,val]) => d3.select("#test").style(prop,val))

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><div id="test"></div>

但是我不太确定这里的性能.

But I'm not quite sure about performance here.

这篇关于在D3.js中使用.style()方法应用多种样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆