Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - Style a d3 element with jQuery and CSS

I have somehow a technical question. I would like to know if there is a possibility to style a d3 element with jQuery.

For instance a "Collatz Graph" example from the d3 site http://www.jasondavies.com/collatz-graph/ is producing a circle - like nodes with small labels.

In that case the numbers 1, 2, 3 and so on. The number is nothing more than a piece of code e.g.

 <text dy=".31em" text-anchor="start" transform="rotate(90)translate(8)">32</text>

How could I style this element with jQuery? e.g. adding a red border by clicking it?

Obviously I would need a class or id in the <text ... > and proceed as follows:

 $(".nome_class").click(function() {
    $(this).css( "border", "3px solid red" );
 }); 

In my code, both d3 is working (I can see a graph) and jQuery is working (I can for instance style or do something else with the regular HTML elements). BUT when I try style d3 element I get no result.

I will be very grateful for any hint or advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can, however when targeting <svg> elements, you must chose style properties such as stroke and fill. For example, in that site, if you open up your dev tools and paste/execute the following, you'll see the changes

$('circle').css('stroke', 'green')
$('circle').css('fill', 'red')

Edit

Per discussion you can attach event handlers on your <g> elements with jQuery and do whatever else you wish

$('g').click(function(e) {
    console.log($(this).children().closest('text').text());
    // do whatever else  
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...