我有以下简单的例子.它存储在image.svg中:
<svg>
<defs>
<g id="shape">
<circle cx="100" cy="100" r="100" />
</g>
</defs>
</svg>Run Code Online (Sandbox Code Playgroud)
但是,将此代码放在HTML文件中不会加载任何内容.这是为什么?
<svg>
<use xlink:href="#shape" x="10" y="10" />
</svg>
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我似乎无法使其发挥作用.
如果您使用其他文档中的元素,则必须指定文档!
<use xlink:href="#shape" x="10" y="10" />
Run Code Online (Sandbox Code Playgroud)
这意味着"使用#shape当前文档中的元素".
要从另一个文档导入,您需要在xlink:href属性中添加对SVG文件的引用:
<use xlink:href="image.svg#shape" x="10" y="10" />
Run Code Online (Sandbox Code Playgroud)
显然你需要在这里检查路径是否正确.请注意,虽然可以使用polyfill,但在任何版本的Internet Explorer中都不支持此功能.
对于外部svg文件,你需要命名空间...我添加了一个填充来渲染圆圈,否则它将是透明的:
<svg xmlns="http://www.w3.org/2000/svg" >
<symbol id="shape" width="200" height="200" viewbox="0 0 200 200">
<circle cx="100" cy="100" r="100" fill="currentColor" />
</symbol>
<text y="20">Symbol above will not render unless referenced by use element</text>
</svg>Run Code Online (Sandbox Code Playgroud)
然后,当您引用它时,您需要为xlink使用正确的命名空间:
svg.defs-only {
display:block; position: absolute;
height:0; width:0; margin: 0; padding: 0;
border: none; overflow: hidden;
}
svg {
color: orange;
stroke: red;
}
.purple {
color: purple;
stroke: black;
}Run Code Online (Sandbox Code Playgroud)
<svg class="defs-only" xmlns="http://www.w3.org/2000/svg" >
<symbol id="shape" width="50" height="50" viewbox="0 0 50 50">
<circle cx="25" cy="25" r="20" fill="currentColor" stroke="inherit" />
</symbol>
</svg>
<svg xmlns:xlink="http://www.w3.org/1999/xlink">
<use xlink:href="#shape" x="10" y="10" />
<use xlink:href="#shape" x="80" y="10" class="purple" />
</svg>Run Code Online (Sandbox Code Playgroud)
如果您正在引用外部文件,则需要在文件名之前放置文件名,#例如image.svg#shape确保路径正确无误.
请注意,并非所有浏览器都支持片段标识符 - 尤其是IE和Edge - 您需要为这些浏览器使用svg4everybody等javascript polyfill.
解决方法 - 仅使用svg内联
您需要在 SVG 中包含您要使用的形状的 use 标签:
<svg>
<defs>
<g id="shape">
<circle cx="100" cy="100" r="100" />
</g>
</defs>
<use xlink:href="#shape" x="10" y="10" />
</svg>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7712 次 |
| 最近记录: |