使用<symbol>编写SVG脚本

Bra*_*ods 8 javascript svg

我正在尝试在JS中创建一个SVG元素,然后将其附加到DOM.SVG元素引用了一个符号.我可以使用该insertAdjacentHTML方法实现此目的,但不能通过appendChild方法实现.

在使用时appendChild,根据浏览器检查员,所有正确的东西都在DOM上,但它没有正确呈现.谁能明白为什么?

http://codepen.io/bradjohnwoods/pen/dGpqMb?editors=101

<svg display="none">
  <symbol id="symbol--circle--ripple" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="25" />
  </symbol>
</svg>

<button id="btn">
</button>

<script>
var btn = document.getElementById('btn');

//var myString = '<svg><use xlink:href="#symbol--circle--ripple" width="100" height="100" class="btn--ripple__circle"></use></svg>';
//btn.insertAdjacentHTML('afterbegin', myString);

var svg = document.createElement('svg');
var use = document.createElement('use');
use.setAttribute("xlink:href", "#symbol--circle--ripple");
use.setAttribute("width", "100");
use.setAttribute("height", "100");
use.classList.add("btn--ripple__circle");

svg.appendChild(use);
btn.appendChild(svg);
</script>
Run Code Online (Sandbox Code Playgroud)

Rob*_*son 5

您不能createElement使用createElementNS来创建 SVG 元素,而必须使用来在 SVG 命名空间中创建它们

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
Run Code Online (Sandbox Code Playgroud)

insertAdjacentHTML 调用 html 解析器,它神奇地修复了元素命名空间。

同样,您不能使用 setAttribute 在 xlink 命名空间中创建属性,例如 xlink:href。你要

setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#symbol--circle--ripple");
Run Code Online (Sandbox Code Playgroud)

那里