使用 Web 组件创建内联 SVG,可使用属性进行配置。
customElements.define("my-svg", class extends HTMLElement {
connectedCallback(){
this.style.display = "inline-block";
this.style.width = "100px";
this.style.background = "pink";
this.innerHTML = `<svg viewBox="0 0 96 96" style="vertical-align:top">
<circle cx="50%" cy="50%" r="50%"
fill="${this.getAttribute("fill") || "red"}"></circle>
</svg>`
}
});
<my-svg></my-svg>
<my-svg fill="yellow"></my-svg>
<my-svg fill="blue"></my-svg>
您的
id
问题是因为内联 SVG 将使用页面上第一个定义的 id
。
要解决此问题,请在上面的 Web 组件中创建一个唯一的
id