我想在localStorage中将SVG图标存储为<symbol>
标记,然后在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);
&#13;
#sprites {
dispay: none;
}
svg {
border: 2px solid black;
}
&#13;
<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>
&#13;
为什么没有出现黄色圆圈?
我怀疑是否与黄色圆圈的<svg>
元素有关,而不是在页面底部显示为150x300框(这使我感到困惑,因为两个<svg>
元素都是一个带display: none
的div,两者都不可见。
答案 0 :(得分:1)
如果你调试document.createElement('svg').constructor
,你会发现它实际上是HTMLUnknownElement
创建的:
> document.createElement('svg').constructor;
< ƒ HTMLUnknownElement() { [native code] }
这是因为SVG不是HTML的一部分;它必须被命名空间才能工作。试试这个:
document.createElementNS("http://www.w3.org/2000/svg", "svg");