I created an SVG file that I intend to use as a background image in CSS. I want to be able to change the fill color in SVG using the query string parameter, for example:
#rect { background-image: url( 'rect.svg' ); } #rect.red { background-image: url( 'rect.svg?color=red' ); }
As I understand it, using the script tag in SVG, I can get the color parameter and update the fill color. Here is an example SVG:
<!DOCTYPE svg PUBLIC "-//W3C//DDTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect width="100%" height="100%" /> <script> <![CDATA[ var params = { }; location.href.split( '?' )[1].split( '&' ).forEach( function( i ) { params[ i.split( '=' )[0] ] = i.split( '=' )[1]; } ); if( params.color ) { var rect = document.getElementsByTagName( "rect" )[0]; rect.setAttribute( "fill", params.color ); } ]]> </script> </svg>
Going to the file directly or using an object tag seems to work, but for CSS background images or img tags, the color option is ignored.
I'm not quite sure what is happening here, and I was hoping there would be an explanation or alternative solution to what I was trying to accomplish (preferably without resorting to server processing).
Here is jsFiddle showing different rendering methods: http://jsfiddle.net/ehb7S/
source share