代码之家  ›  专栏  ›  技术社区  ›  crenshaw-dev

将SVG作为字符串插入是可行的,但不能作为元素插入

  •  0
  • crenshaw-dev  · 技术社区  · 6 年前

    我想将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 ,两者都不应可见)。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Máté Safranka    6 年前

    如果你调试 document.createElement('svg').constructor ,你会看到它实际上是作为 HTMLUnknownElement :

    > document.createElement('svg').constructor;
    < ƒ HTMLUnknownElement() { [native code] }
    

    这是因为SVG不是HTML的一部分;它必须有名称空间才能工作。试试这个:

    document.createElementNS("http://www.w3.org/2000/svg", "svg");