程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了替代 <use/> 以避免在重复内联 SVG 时重复 id大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决替代 <use/> 以避免在重复内联 SVG 时重复 id?

开发过程中遇到替代 <use/> 以避免在重复内联 SVG 时重复 id的问题如何解决?下面主要结合日常开发的经验,给出你关于替代 <use/> 以避免在重复内联 SVG 时重复 id的解决方法建议,希望对你解决替代 <use/> 以避免在重复内联 SVG 时重复 id有所启发或帮助;

Plunkr 示例。

所以假设我有 svg,我在 HTML 中包含内联

      <svg xmlns="http://www.w3.org/2000/svg" wIDth="100" height="100" vIEwBox="0 0 100 100" class="col-sm-3">
        <symbol ID="circle" vIEwBox="0 0 50 50">
          <circle cx="25" cy="25" r="25" fill="white" stroke="black" stroke-wIDth="2"></circle>
          <text x="50%" y="50%" text-anchor="mIDdle" dy=".3em">___THIS_IS_A_VARIABLE__</text>
        </symbol>
        <use xlink:href="#circle" wIDth="85"  height="85"/>
      </svg>

我有一个稍微复杂的使用注意事项,其中 <symbol/> 的内部是与 svg 根视图框不同比例的复杂路径,因此我需要使用 <symbol/> 将其缩放为全尺寸。

我需要通过 for 循环在我的 HTML 中包含一堆这些。一切正常,但我担心我将来可能会引入错误,因为在我的 HTML 文档中,我有多个具有相同 ID 的元素。

我的问题:

  • 是否有其他方法可以像使用 CSS 选择器一样使用 <use/>
  • 在 HTML 文档内的内联 SVG 中重复 ID 与在 HTML 文档本身中重复 ID 一样糟糕,我是否正确?
  • 是否有更好的方法来嵌套 vIEwBox 属性以避免 <use/>

解决方法

我能想到的最好方法是使 id 动态化。因此,在使用 angular 的情况下,它将是:

      <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" class="col-sm-3">
        <symbol [id]="circlEID" viewBox="0 0 50 50">
          <circle cx="25" cy="25" r="25" fill="white" stroke="black" stroke-width="2"></circle>
          <text x="50%" y="50%" text-anchor="middle" dy=".3em">___THIS_IS_A_VARIABLE__</text>
        </symbol>
        <use [attr.xlink:href]="'#' + circlEID" width="85"  height="85"/>
      </svg>
,

不需要框架,原生 W3C Web Components 也能做到:

如果您不/不能指定 ID,请生成一个:let id = "id" + new Date()/1;

@H_772_54@svg { display: inline-block; BACkground: grey; }
<svg-shape id=1 text="red"></svg-shape>
<svg-shape id=2></svg-shape>
<svg-shape id=3 text="blue"></svg-shape>
<script>
  customElements.define('svg-shape',class extends HTMLElement {
    connectedCallBACk() {
      let id = this.getAttribute("id");
      let text = this.hasAttribute("text") ? this.getAttribute("text") : "";
      this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100" class="col-sm-3">
        <symbol id="id${iD}" viewBox="0 0 50 50">
          <circle cx="25" cy="25" r="25" fill="white" stroke="${text}" stroke-width="2"></circle>
          <text x="50%" y="50%" text-anchor="middle" dy=".3em">${text}</text>
        </symbol>
        <use href="#id${iD}" width="85"  height="85"/>
      </svg>`;
      this.onclick = (evt) => console.log('clicked',id);
    }
  });
</script>

大佬总结

以上是大佬教程为你收集整理的替代 <use/> 以避免在重复内联 SVG 时重复 id全部内容,希望文章能够帮你解决替代 <use/> 以避免在重复内联 SVG 时重复 id所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:id替代