简体   繁体   English

将样式表用于从内容加载的SVG

[英]Using style sheet for SVG loaded from content

I have a circle.svg file 我有一个circle.svg文件

<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 还有一个HTML文件

...
<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. 但是,如果将svg代码嵌入HTML,则样式表将对其生效,但是我不想在HTML代码中插入额外的资源。 Is there a way to do it via CSS? 有没有办法通过CSS做到这一点? If not, how about using JavaScript? 如果没有,那如何使用JavaScript?

Styles don't apply across documents and the SVG and HTML you have there are separate documents. 样式不适用于所有文档,并且您拥有的SVG和HTML是单独的文档。

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 如果通过两个<object><iframe>标记嵌入圆圈,则可以执行所需的操作,因为您可以访问和操作SVG DOM,即

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. 同样,其他<object>标签也是如此。

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. 我不认为如果将svg设置为外部资源,则可以使用css或javascript修改其内部属性,这就像尝试使用css样式化iFrame一样。

several solutions : 几种解决方案:

  1. Embed your SVGs in your html 将SVG嵌入到html中
  2. create a sprite from the SVG with a blue and red circle and only move the background-position 从SVG创建带有蓝色和红色圆圈的精灵,仅移动背景位置
  3. create multiple SVG and call them separately depending on the class. 创建多个SVG并根据类分别调用它们。 Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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