我想将 SVG 图标存储为 <symbol>
在 localStorage 中标记,然后将它们插入到 DOMContentLoaded
之后.
理想情况下,我会使用 document.createElement('svg')
并在 document.body
中的第一个节点之前插入元素.
但是(至少在 Chrome 中)图标不会出现,除非我将一个 div 的 innerHTML 设置为 <svg>
的字符串表示形式。元素 然后将 div 插入到文档中。
这是一个简化的例子:
var sprites = document.getElementById('sprites');
var circles = [
'<symbol id="circle-yellow"><circle cx="25" cy="25" r="20" fill="yellow" /></symbol>',
'<symbol id="circle-blue"><circle cx="25" cy="25" r="20" fill="blue" /></symbol>'
];
// Insert the yellow circle symbol by creating an SVG element.
var yellowDiv = document.createElement('div');
var yellow = document.createElement('svg');
yellow.innerHTML = circles[0];
yellowDiv.appendChild(yellow);
sprites.appendChild(yellowDiv);
// Insert the blue circle symbol by inserting the SVG string.
var blueDiv = document.createElement('div');
blueDiv.innerHTML = '<svg>' + circles[1] + '</svg>';
sprites.appendChild(blueDiv);
#sprites {
dispay: none;
}
svg {
border: 2px solid black;
}
<svg height="50" width="50"><use href="#circle-yellow"></use></svg>
<svg height="50" width="50"><use href="#circle-blue"></use></svg>
<!-- Will hold <svg> elements referred to by <use> elements. -->
<div id="sprites"></div>
为什么没有出现黄色圆圈?
我怀疑这与 <svg>
有关黄色圆圈的元素在页面底部没有显示为 150x300 框(这让我感到困惑,因为 <svg>
元素都是带有 display: none
的 div 的子元素,并且都不应该是可见的)。
最佳答案
如果调试 document.createElement('svg').constructor
,您会看到它实际上是作为 HTMLUnknownElement
创建的:
> document.createElement('svg').constructor;
< ƒ HTMLUnknownElement() { [native code] }
这是因为 SVG 不是 HTML 的一部分;它必须命名空间才能工作。试试这个:
document.createElementNS("http://www.w3.org/2000/svg", "svg");
关于javascript - 将 SVG 作为字符串插入有效,但不能作为元素插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50633413/