简体   繁体   中英

How can I add external stylesheet into a svg file?

I want to add a style-sheet into svg file. And the style-sheet will be change dynamically. Because my idea is I want to change the icons fill or stock color by changing theme. What is the process I need to follow?

OK, so you would just control the SVG and its elements like any other element on the page, this is assuming your SVG is inline.

So say we have our svg:

<svg id="my_icon" class="red-theme" height="100" width="100" fill="red">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" />
</svg>

And we had 2 themes, red theme and a blue theme. Then we would create the 2 styles in CSS:

.red-theme{
  fill: red;
}
.blue-theme{
  fill: blue;
}

We can then use jQuery (in this example but you could use other options) to dynamically change the theme by changing the svg's theme on a button press.

$('button').click(function(){
  var p_class = $('#my_icon').attr('class')
  if (p_class == 'red-theme'){
    $('#my_icon').attr('class', 'blue-theme')
  } else {
    $('#my_icon').attr('class', 'red-theme')
  }
});

All together it would look something like this:

http://codepen.io/ballerton/pen/GZGrZe

Hope this helps.

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