SVG 片段标识符用于链接到 SVG 文档的特定 View 。它们在 Secion 17.3.2 of the SVG specification 1.1 中定义.
通常它们的形式为 MyDrawing.svg#MyView
,其中散列后的部分指定链接文档中元素的 ID。但在我看来,像 MyDrawing.svg
这样没有散列的片段标识符也应该被允许。
规范是这样说的:
"If no SVG fragment identifier is provided (e.g, the specified IRI did not contain a "#" character, such as MyDrawing.svg), then the initial view into the SVG document is established using the view specification attributes (i.e., ‘viewBox’, etc.) on the outermost svg element."*
测试用例
如果已经为此设置了一个小测试,一个 HTML 文件链接到两个 SVG 文件。第一个文件是使用片段标识符 img1.svg#id1
的链接,第二个文件是使用标识符 img2.svg
链接的文件:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fragment Identifier Test</title>
</head>
<body>
<h2>With Hash</h2>
<div>
<svg style="width: 128px; height: 128px;">
<use xlink:href="img1.svg#id1"></use>
</svg>
</div>
<h2>Without Hash</h2>
<div>
<svg style="width: 128px; height: 128px;">
<use xlink:href="img2.svg"></use>
</svg>
</div>
</body>
</html>
img1.svg(svg 元素有一个 id)
<svg id="id1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0,0,512,512">
<circle cx="256" cy="256" r="200" fill="green" />
</svg>
img2.svg(svg 元素没有 id)
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0,0,512,512">
<circle cx="256" cy="256" r="200" fill="red" />
</svg>
问题是什么
所有浏览器只显示第一个 SVG。
我的问题是什么?
我的第一个问题是:我的理解是否正确,根据 SVG 规范,没有散列的片段标识符应该是可能的?
我的第二个问题:我在测试用例中做错了什么,还是浏览器不支持这个?
我们为什么要这个?
在我看来,使用不带散列的片段标识符链接 SVG 文档是将单个 SVG 图像添加到 HTML 文档的 chalice 。 原因是:
- 将 SVG 图像包含到 HTML 文档中的简单语法
- 没有不必要的 ID 使 DOM 困惑
- 能够使用 CSS 变量设置 SVG 样式(如 this article on Medium 中所示)。
简而言之,我们终于可以使用可以存储在单个外部文件中的完全 CSS 样式化的矢量图形。没有注入(inject),没有困惑的 DOM ID。
最佳答案
片段标识符是everything after a hash . MyDrawing.svg 根本不是片段标识符。
在 SVG 1.1 中 <use>
元素不能指向 complete file即 MyDrawing.svg
Unlike ‘image’, the ‘use’ element cannot reference entire files.
SVG 2 提议取消该限制,但目前还没有浏览器实现 SVG 2 的这一部分。SVG 2 规范将不得不恢复为 SVG 1.1 文本,除非至少有 2 个浏览器实现了更改。
要在 SVG 1.1 中执行此操作,您需要使用 <image>
正如规范本身所暗示的那样。或者,如果您想使用 <use>
元素,在根元素上放置一个 id 并指向 <use>
元素。
关于svg - 为什么没有散列的 SVG 片段标识符不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896563/