背景图像的编码 SVG 可以从单独的文件中导入吗?

Can an encoded SVG for background-image be imported from a separate file?

我有一个 SVG 文件:

myIcon.svg

<svg>.....</svg>

我想在我的 css:

中使用它
   .body {
       background-image: url(../myIcon.svg);
   }

由于需要对 svg 进行编码才能用作背景图像,因此我得到了这样的结果:

.body {
    background-image: url("data:image/svg+xml,***<here place encoded svg>***");
}

有没有办法将编码后的 svg 存储在它自己的文件中以便于维护?由于它不在 html 标签中,我不确定如何将它保存到它自己的文件中,或者是否可能。

花一些时间调查 不允许data:image/svg URI
中使用哪些字符 许多编码器转换 <>,但它们是有效的。

  • 加载您的外部 SVG 文件并替换所有无效字符

  • 使用 background-image

    创建一个新的 <style> 元素

包装在现代 Web 组件中,因此完全无关紧要何时执行脚本

⚠️ xmlns="http://www.w3.org/2000/svg" 必须出现在SVG文件中;在现代浏览器中 inline SVG 时不需要它。

<svg-import-background src="//svg-cdn.github.io/red.svg" selector="#container"></svg-import-background>
<svg-import-background src="//svg-cdn.github.io/yellow.svg" selector="div > h2"></svg-import-background>
<svg-import-background src="//svg-cdn.github.io/blue.svg" selector="pre"></svg-import-background>

<style>
  body { font:16px Arial; color:beige }   h2   { color: black }
</style>

<div id="container">
  <h2>Web Component &lt;svg-import-background&gt;</h2>
  Inject external SVG file into CSS background-image
  <pre>
&lt;svg-import-background ATTRIBUTES:
                                   src="PATH TO SVG FILE"
                                   selector="Element selector"
  </pre>
</div>

<script>
  customElements.define("svg-import-background", class extends HTMLElement {
    async connectedCallback() {
      let svg = await (await fetch(this.getAttribute("src"))).text();
      svg = svg.replace(/\>[\t\s\n ]+\</g, "><"); // replace all BETWEEN tags
      svg = svg.replace(/#/g, "%23");
      svg = svg.replace(/"/g, "'");
      this.innerHTML = `<style>${this.getAttribute("selector") || "body"}{`+
        `background-image:url("data:image/svg+xml;charset=UTF-8,${svg}")`+
      `}</style>`;
    }
  })
</script>

<svg viewBox="0 0 8 8"><rect width="100%" height="100%" fill="gold"></rect></svg>

回复:encodeURIComponent

是的,您可以将所有 3 replace 语句替换为:

svg = encodeURIComponent(svg);

不同之处在于在您的 HTML 代码中注入了什么。

3replace语句注入:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><rect width='100%' height='100%' fill='%23f00'></rect></svg>

encodeURIComponent 注入:

%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%208%208%22%3E%0A%20%20%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22%2300f%22%3E%3C%2Frect%3E%0A%3C%2Fsvg%3E

你想调试哪一个取决于你