我正在嘗試tspan在 SVG 檔案中定義早期,以便稍后可以將其嵌入到text. 至少在 Firefox 中,以下代碼不會產生這種結果。
<svg version="1.1" width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<defs>
<tspan id="transcluded-text">This is a text</tspan>
</defs>
<text>
<use href="#transcluded-text"/>
</text>
</svg>
使用 Firefox 的 Inspect 工具,該use元素#shadow-root按預期包含一個 shadow DOM ( ),但 shadow DOM 本身是空的。
不使用 Javascript,是否可以像這樣嵌入 atspan內部text?
uj5u.com熱心網友回復:
該文本元素只能包含文本內容的子元素(所以,不是<use>)和純文本相關的元素DEFS元素可以包含的<text>。所以,這一切都表明<tspan>不能以這種方式使用。
<svg version="1.1" width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<defs>
<text x="10" y="20" font-size="20" id="transcluded-text">This is a text</text>
</defs>
<use href="#transcluded-text"/>
</svg>
uj5u.com熱心網友回復:
由于您不能在<use>元素內使用<text>元素;
或裸露的<tspan>內在<defs>
現代原生Web 組件可以完成替換作業:
(這將導致您可能想要處理的 FOUC)
<script>
customElements.define("svg-use-replacer", class extends HTMLElement {
connectedCallback() {
setTimeout(() => { // make sure SVG is parsed
this.querySelectorAll('use').forEach(use => {
let href = use.getAttribute("href");
let tspan = this.querySelector(href);
use.replaceWith(tspan); // .replaceWith was not available in IE
});
// if the bare <svg> is required in the DOM:
// this.replaceWith(this.querySelector("svg"));
});
}
});
</script>
<svg-use-replacer>
<svg version="1.1" width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<defs>
<tspan id="foo" stroke="green">Wonderful</tspan>
</defs>
<text x="10" y="20" font-size="20">
Hello
<use href="#foo" /> Web Component
</text>
</svg>
</svg-use-replacer>
筆記
oldskool 方法是附加一個類,然后在決議 Element 之后在其上運行 JavaScript。
對于 Web 組件,何時定義Web 組件完全無關緊要。
您可以隨時執行上述操作script。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/385131.html
標籤:svg
上一篇:無論如何要在帶有AppleSilicon(M1、M1Pro、M1Max)GPU的Mac中使用Tensorflow?
