简体   繁体   中英

svg, color group child elements

I created a SVG out of illustrator. The elements have the fill on the paths. I am trying to change the color based on the group id that the path is in.

I would like to change all child elements fill colors in the same group to the same color when an event happens.

Here is a jsFiddle: http://jsfiddle.net/cdcgbu6g/6/

function ChangeColor(zone,color,colorCode) {
document.getElementById(zone).children().css( "fill", colorCode );
};

The javascript would be in an external .js file.

When you click a color square, the fill value on the two objects should change that are under the group id of "Color_1".

Everything I read says this should work.

As stated by @Paul LeBeau your first snippet did work well, just a jsFiddle configuration issue.

However, while revising your post, you brought a new error :

function ChangeColor(zone,color,colorCode) {
   document.getElementById(zone).children().css( "fill", colorCode );
};

This code won't work because you are trying to call jQuery methods ( .children() and .css() ) on a non jQuery object ( document.getElementById() does return a DOM object ).

You could rewrite this function to :

function ChangeColor(zone,color,colorCode) {
  $('#'+zone).children().css( "fill", colorCode );
};

Now we're calling a jQuery object and everything works well, just like in your first snippet where you weren't using jQuery.

Your fiddle works fine if you change when the Javascript gets run. If you change it to one of the No wrap options, all is well.

http://jsfiddle.net/cdcgbu6g/4/

Update: why is this?

I haven't looked at what exactly jsfiddle is doing, but I imagine that it works something like the following:

When you use the "onLoad" option, it is doing something equivalent to the following:

window.onload = function() {
   // users fiddle JS here
};

That means that any functions you define (ie. ChangeColor() ) will be defined inside the ready function's namespace and won't be visible to the HTML event handlers.

There are two alternatives solutions. Change the run mode to one of the two "No wrap" options as I suggested above.

Alternatively you could stay with "onLoad" mode and force the function into the global namespace (window), or another namespce under that.

window.ChangeColor = function(zone,color,colorCode) {
    document.getElementById(zone).style.fill = colorCode;
};

http://jsfiddle.net/cdcgbu6g/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM