【发布时间】:2021-05-27 16:40:20
【问题描述】:
我有一个带有嵌入式 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 -->❓
</h2>
<p>def</p>
</body>
</html>
现在我想在第二个标题中重用嵌入的 SVG 图标。如何做到这一点?
【问题讨论】:
-
如果它是内联的,那么你不能引用它。所以你必须克隆它。更好的方法是使用 svg 作为背景图形。这样你就可以在你的样式中指定一次,但这确实不是内联的。
-
@arkascha 我想为图标添加事件处理程序。我不确定,如果使用背景图片可以做到这一点?
-
显然不适用于背景元素。然后尝试使用
::after或 ::before` 伪元素。您可以使用 svg 作为背景,指定特定大小并将 js 处理程序附加到伪元素。或者您只需将 svg 引用为图像。只会加载一次,因为它在本地缓存并且还允许附加事件处理程序。 -
@arkascha 不可能将事件处理程序附加到伪元素,因为它们也没有 DOM 节点。
-
这也是真的,是的。但是你不能在伪元素中放置一个透明元素,比如透明跨度并附加一个处理程序吗?