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

标签 html css svg

我有一个要在网页中使用的 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 中的所有其他原因。 :)

关于html - 我可以在页面中重复使用相同的 SVG 并应用不同的 CSS 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25078634/

相关文章:

javascript - IE 9下本地存储大小不受限制?

java - 开发网络摄像头聊天应用程序

jquery - 在输入字段中捕获制表键并移动到页面上的特定元素

html - 垂直对齐表格中的图像

html - 固定宽度的 facebook 标题

javascript - 放置带有一些关键值的空格

css - 使用 CSS 的 HTML 表单布局

css - 在 ie9 中不遵守 img 元素比例中的 SVG

javascript - 第 1 行第 1 列错误 : Document is empty

javascript - HTML 视频在 svg 中的 foreignObject 中不可见