我有一個 SVG 檔案:
我的圖示.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 標簽中,我不確定如何將它保存到它自己的檔案中,或者是否有可能。
uj5u.com熱心網友回復:
花一些時間研究URI中不允許使用的字符
許多編碼器轉換和,但這些字符是有效的。data:image/svg<>
加載您的外部 SVG檔案并替換所有無效字符
創建一個新
<style>元素background-image
包裝在現代 Web 組件中,因此腳本何時執行完全無關緊要
??xmlns="http://www.w3.org/2000/svg" 必須存在于 SVG 檔案中;在現代瀏覽器中行內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 <svg-import-background></h2>
Inject external SVG file into CSS background-image
<pre>
<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, "#");
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 代碼中注入的內容。
3 條replace陳述句注入:
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><rect width='100%' height='100%' fill='#f00'></rect></svg>
encodeURIComponent注入:
由您決定要除錯哪一個
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441108.html
上一篇:Unit型別的列舉
