SVG 使用多个,加载一次

use*_*445 3 html javascript css svg

我想在我的页面上使用相同的 SVG 两次,但只加载一次。

我正在用 JS 操作 SVG 的 CSS,所以我认为 SVG 需要直接在 HTML 中,而不是使用对象。

两个 SVG 的操作是相同的,它们应该是精确的副本,所以我真的不想加载它两次。

我有什么办法可以做到这一点?

谢谢,詹姆斯

Bob*_*nge 5

svg {
   color: green;
   width: 20px;
   height: 20px;
}
Run Code Online (Sandbox Code Playgroud)
<!-- define SVGs -->
<div style="visibility: hidden; position: absolute; width: 0px; height: 0px;">
  <svg xmlns="http://www.w3.org/2000/svg">
  <symbol viewBox="0 0 18 15" id="sample">
    <path d="M17.9 1.85L7.675 12.318 6 14.03l-1.676-1.713L.1 8.002c-.15-.162-.146-.43.01-.597l1.07-1.15c.155-.168.403-.172.554-.01L6 10.605 16.266.094c.15-.163.4-.16.555.008l1.07 1.152c.156.167.16.435.01.596z" fill="currentColor" fill-rule="evenodd"></path>
    </symbol>
  </svg>
</div>

<!-- and use it whenever you want -->
<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>

<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>
Run Code Online (Sandbox Code Playgroud)