gpt4 book ai didi

javascript - 使用 编写 SVG 脚本

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:54 24 4
gpt4 key购买 nike

我正在尝试在 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>

最佳答案

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

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');

insertAdjacentHTML 调用神奇地修复元素 namespace 的 html 解析器。

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

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

那里

关于javascript - 使用 <symbol> 编写 SVG 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com