如何将“所需”id 传递给由多个 g 组成的内联 SVG?

问题描述 投票:0回答:1
html svg dom inline
1个回答
1
投票

使用 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

或者向您的 Web 组件添加额外的 ShadowRoot 来封装所有内容。
请参阅:是否可以在 SVG 中使用动态 id fill=url(#)

© www.soinside.com 2019 - 2024. All rights reserved.