我有一个SVG文件,我想在网页中使用.我希望图像多次出现,但要为每个图像应用不同的CSS样式.
这可能吗?
当我说"应用不同的CSS样式"时,我的意思是我想要设置SVG内容的样式(笔触,颜色,半径等),而不仅仅是一个<img>
或者某个东西的宽度.
另外,我不认为"复制并粘贴SVG内容"是"重新使用"它.我想创建一个类似的文件logo.svg
,并从HTML中引用它.
Nat*_*ong 11
目前不支持从包含HTML文档中定制SVG的内容(笔触,填充等).
@RobertLongson非常友好地指出了SVG参数规范,它可以提供部分解决方案.它没有在任何浏览器中实现,但可以与Javascript垫片一起使用.但是,当我通过电子邮件向SVG工作组发送有关它的问题时,我被告知:
SVG参数文档目前已过期.目前的计划是将其与CSS Custom Properties和var()集成; 然后,规范将成为定义自定义属性的替代方法.
和
SVG <img> s实际上完全在一个单独的文件中; 它与<iframe>基本相同,只是更严格地锁定.出于安全性,理智性和性能原因的结合,我们不允许跨文档边界进行直接选择.
也就是说,参数规范定义一种从引用环境中获取值的方法似乎是合理的,所以你要在<img>本身设置属性,它将根据文档的请求转移到包含的文档.
use
标签为了记录,以下似乎完成了我的既定目标(从CSS-Tricks借来的技术),但@RobertLongson让我知道它只适用于Firefox(我认为我使用的是版本31),因为Firefox不符合规范.
<!DOCTYPE html>
<html>
<head>
<title>SVG Reuse Demo</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html" />
<style type="text/css">
.circle .uno { stroke: orange; stroke-width: 5px; }
.circle-1 .uno { fill: blue; }
.circle-2 .uno { fill: red; }
.circle-3 .uno { fill: green; }
</style>
</head>
<body>
<!-- Single definition of SVG -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="disc" viewbox="0 0 100 100">
<circle class="uno" cx="50" cy="50" r="40">
</symbol>
</svg>
<!-- Re-use; each is styled differently (see above) -->
<svg class="circle circle-1">
<use xlink:href="#disc">
</svg>
<svg class="circle circle-2">
<use xlink:href="#disc">
</svg>
<svg class="circle circle-3">
<use xlink:href="#disc">
</svg>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
即使它是标准的,这种技术也不太理想; 理想的解决方案是允许使用外部文件中定义的SVG ,例如circles.svg
.
这是因为:
是的,它可以使用 SVG 注入轻松完成,并且它应该适用于所有支持 SVG 的浏览器。
使用SVGInject,您的 HTML 可能如下所示:
<html>
<head>
<script src="svg-inject.min.js"></script>
<style>
.redImage {
/* Your CSS for the red image here */
}
.greenImage {
/* Your CSS for the green image here */
}
<style>
</head>
<body>
<img class="redImage" src="image.svg" onload="SVGInject(this)" />
<img class="greenImage" src="image.svg" onload="SVGInject(this)" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在onload="SVGInject(this)"
加载 SVG 后触发注入,并使用<img>
指定 SVG 文件中的 SVG 标记替换元素。