如何在同一页面中重用嵌入的 SVG 元素?

cev*_*ing 5 html svg

我有一个带有嵌入式 SVG 图标元素的简单 HTML5 页面。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgo=">
  </head>
  <body>
    <h1>
      <span>ABC</span>
      <svg id="move-icon"
           width="0.7em" height="0.7em"
           viewBox="0 0 10 10"
           style="display: inline-block">
        <defs>
          <marker id="arrow-end-marker"
                  viewBox="0 0 10 10" refX="0" refY="5"
                  markerHeight="3"
                  orient="auto">
            <polygon points="0 0 10 5 0 10" />
	  </marker>
        </defs>
        <line x1="5" y1="5" x2="5" y2="7"
              stroke="black" stroke-width="0.03em"
              marker-end="url(#arrow-end-marker)" />
        <line x1="5" y1="5" x2="3" y2="5"
              stroke="black" stroke-width="0.03em"
              marker-end="url(#arrow-end-marker)" />
        <line x1="5" y1="5" x2="5" y2="3"
              stroke="black" stroke-width="0.03em"
              marker-end="url(#arrow-end-marker)" />
        <line x1="5" y1="5" x2="7" y2="5"
              stroke="black" stroke-width="0.03em"
              marker-end="url(#arrow-end-marker)" />
      </svg>
    </h1>
    <p>abc</p>
    <h2>
      <span>DEF</span>
      <!-- reuse here -->&#10067;
    </h2>
    <p>def</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在我想在第二个标题中重用嵌入的 SVG 图标。如何才能做到这一点?

Mil*_*kus 21

symbol+ use+href="#symbol-id"

定义一个符号一次,并在其他 svg 文档中使用它

<!-- define symbol in hidden svg document -->
<svg style="display: none" version="2.0">
  <defs>
    <symbol id="circle-arrow-left" viewbox="0 -10 100 110">
      <path d="m 20 80 A 40 40 0 1 0 20 20"
        fill="none" stroke="#000" stroke-width="10" />
      <path d="M 10 0 v 40 h 40"
        fill="#000" />
    </symbol>
  </defs>
  <!-- to make the circle-arrow-left.svg file
       also usable as image: -->
  <use href="#circle-arrow-left"/>
</svg>

<!-- use symbol of external svg document -->
<button>
  <svg width="50" height="50" version="2.0">
    <use href="#circle-arrow-left" />
  </svg>
</button>

<!-- transform symbol with horizontal flip -->
<button>
  <svg style="transform: scale(-1, 1)" width="50" height="50" version="2.0">
    <use href="#circle-arrow-left" />
  </svg>
</button>
Run Code Online (Sandbox Code Playgroud)

更改样式:将新样式添加到使用符号的位置:

<svg style="fill: red"><use href="#s1"/></svg>

<svg class="some-class"><use href="#s2"/></svg>
Run Code Online (Sandbox Code Playgroud)

Inkscape中并没有支持<svg version="2.0"><use href="#some-id"/>
对于 svg 1.1 版,我们需要<svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink"><use xlink:href="#some-id"/>

有关的:

https://css-tricks.com/svg-symbol-good-choice-icons/

https://css-tricks.com/svg-use-with-external-reference-take-2/