最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - d3.selectAll to change styles by class in v4 - Stack Overflow

programmeradmin0浏览0评论

I'm transitioning from d3 v3 to d3 v4. I've looked through the documentation on what's changed, and I know that styles and selectors work a little differently now. I'm having an issue finding the right way to get what I need done.

In v3 I could do this:

d3.selectAll(".myRectangle").style({'fill':'rgb(255,100,100)', 'stroke':'#000', 'stroke-width':'0.3'});

at the bottom of my code and everything that was classed as "myRectangle" that had been drawn would get the specified style applied to it.

Also, it would act as a placeholder in case anything dynamically got the myRectangle class added to them (say with a mouseover).

Now, the same code not only doesn't apply the styles, it returns an error if no element with the specified class exists.

I haven't been able to find an example of how to properly achieve this, which, might mean that I've been doing it poorly all along. Can anyone here point me in the right direction?

I'm transitioning from d3 v3 to d3 v4. I've looked through the documentation on what's changed, and I know that styles and selectors work a little differently now. I'm having an issue finding the right way to get what I need done.

In v3 I could do this:

d3.selectAll(".myRectangle").style({'fill':'rgb(255,100,100)', 'stroke':'#000', 'stroke-width':'0.3'});

at the bottom of my code and everything that was classed as "myRectangle" that had been drawn would get the specified style applied to it.

Also, it would act as a placeholder in case anything dynamically got the myRectangle class added to them (say with a mouseover).

Now, the same code not only doesn't apply the styles, it returns an error if no element with the specified class exists.

I haven't been able to find an example of how to properly achieve this, which, might mean that I've been doing it poorly all along. Can anyone here point me in the right direction?

Share Improve this question asked Aug 10, 2016 at 20:06 Michael ConnMichael Conn 1151 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

In d3.js v4, attr and style only accept one attribute/value pair as parameters:

d3.selectAll('.myRectangle').style('fill', 'rgb(255,100,100)')

In order to pass an object with multiple values, you have to use attrs and styles instead of attr and style and also include https://d3js/d3-selection-multi.v0.4.min.js file in your web page.

Alternatively, you may chain several attr, one for each attribute. Idem for style.

Reference: d3-selection-multi

The other post is correct that you can only set one attribute or style to one thing at a time. But "style" is an attribute, which accepts a single string!

d3.selectAll('.myRectangle').attr("style", "fill:rgb(255,100,100);stroke:#000;stroke-width:0.3;")
发布评论

评论列表(0)

  1. 暂无评论