html之我可以在页面中重复使用相同的 SVG 并应用不同的 CSS 吗

yjmyzz 阅读:1080 2023-11-05 18:46:41 评论:0

我有一个要在网页中使用的 SVG 文件。我希望图像出现多次,但要对每个图像应用不同的 CSS 样式。

这可能吗?

澄清

当我说“应用不同的 CSS 样式”时,我的意思是我想设置 SVG 内容的样式(描边、颜色、半径等),而不仅仅是 <img> 的宽度。什么的。

此外,我不认为“复制并粘贴 SVG 内容”是“重复使用”它。我想创建一个类似 logo.svg 的文件并从 HTML 中引用它。

请您参考如下方法:

不,目前没有

当前不支持从包含 HTML 文档的 SVG 内容(描边、填充等)样式化。

@RobertLongson 非常友好地向我指出了 SVG Parameters spec ,这可以提供部分解决方案。它没有在任何浏览器中实现,但可以与 Javascript shim 一起使用。然而,当我通过电子邮件向 SVG 工作组提出相关问题时,我被告知:

The SVG Parameters doc is currently out-of-date. The plan at the moment is to integrate it with CSS Custom Properties and var(); the spec will then become an alternative way to define a custom property.

SVG <img>s are actually in a separate document entirely; it's basically the same as an <iframe>, just locked down more strictly. We don't allow direct selection across document boundaries for a combination of security, sanity, and performance reasons.

That said, it seems reasonable for the Parameters spec to define a way to take values from the referencing environment, so you'd set the property on the <img> itself and it would transfer through to the contained document at the document's request.

一个不符合规范的 hack: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> 

即使它是标准的,这种技术也不太理想;理想的解决方案是允许使用 在外部文件 中定义的 SVG,例如 circles.svg

这是因为:

  1. 将其粘贴到 HTML 中很困惑(我的实际用例可能是 300 行 SVG)
  2. 如果它是一个单独的文件,我可以在其他 HTML 文档中重复使用它
  3. 我可以使用 SVG 特定的语法突出显示来编辑它
  4. 它可以与 HTML 文档分开请求和缓存
  5. ...基本上我们通常将 CSS 和图像放在单独的文件中而不是内嵌在 HTML 中的所有其他原因。 :)


标签:CSS
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

全民解析

全民解析

关注我们