简体   繁体   中英

Using style sheet for SVG loaded from content

I have a circle.svg file

<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink"
  width="48" height="48">
  <circle class="circle" cx="24" cy="24" r="24"></circle>
</svg>

And a HTML file

...
<div class="bullet blue">
  ...
</div>
<div class="bullet red">
  ...
</div>
<style>
.bullet:before {
  content: url(circle.svg);
}
.bullet.blue:before {
  .circle {
    fill: #0000FF;
  }
}
.bullet.red:before {
  .circle {
    fill: #FF0000;
  }
}
</style>

I want the circle be filled by the style sheet, but it's not working. However if I embed the svg code into the HTML, the style sheet would take effect on it, but I don't want to insert extra resources in HTML code. Is there a way to do it via CSS? If not, how about using JavaScript?

Styles don't apply across documents and the SVG and HTML you have there are separate documents.

If you embedded the circles via two <object> or <iframe> tags it would be possible to do what you want as you could access and manipulate the SVG DOM then ie

var svgDoc = document.getElementById("objectId1").contentDocument;
var style = svgDoc.createElementNS("http://www.w3.org/2000/svg". "style");
style.textContent = ".circle { fill: #0000FF; }";
svgDoc.rootElement.appendChild(style);

And similarly for the other <object> tag.

I don't think that if you set the svg as an external resource, you would be able to modify its inner properties with css or javascript It would be like trying to style an iFrame with css.

several solutions :

  1. Embed your SVGs in your html
  2. create a sprite from the SVG with a blue and red circle and only move the background-position
  3. create multiple SVG and call them separately depending on the class. Hope that 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