繁体   English   中英

为什么未显示使用 JavaScript 创建的 SVG use 元素?

[英]Why SVG use element created with JavaScript is not shown?

我的文档中有一个 SVG,我用 JavaScript 向它添加了一个符号,如下所示:

var myScene =document.getElementById('myScene');
var useSVG = document.createElement('use');
useSVG.setAttribute('xlink:href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);

符号不显示,而生成的代码与正确显示的另一个用 HTML 编写的节点完全相同。

调试器中显示的代码:

<svg id="myScene" width="200px" height="200px">
    <use xlink:href="spriteSheet.svg#mySymbol" x="5" y="50" width="10" height="10"></use>
    <!-- this one was in html, it is visible -->
    <use xlink:href="spriteSheet.svg#mySymbol" x="10" y="30" width="10" height="10"></use>
    <!-- this one is added with javascript. it is not displayed -->
</svg>

您需要使用createElementNS()来创建 SVG 元素。 基本的createElement()在 HTML 命名空间中创建元素。 所以你基本上一直在创建<html:use>元素而不是<svg:use>元素。

var myScene =document.getElementById('myScene');
var useSVG = document.createElementNS('http://www.w3.org/2000/svg', 'use');
useSVG.setAttributeNS('http://www.w3.org/1999/xlink','href','spriteSheet.svg#mySymbol');
useSVG.setAttribute('x','10');
useSVG.setAttribute('y','30');
useSVG.setAttribute('width','10');
useSVG.setAttribute('height','10');
myScene.appendChild(useSVG);

演示在这里

更新

我刚刚意识到您的代码存在第二个问题。 您在href中使用了外部引用(它引用了另一个文件中的符号)。 IE 似乎不支持外部引用。

我在这里找到了更多信息和可能的解决方法: http : //css-tricks.com/svg-use-external-source/

我不确定 100% 但我认为您需要使用setAttributeNS()设置xlink:href属性,如下所示:

useSVG.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'spriteSheet.svg#mySymbol');

还要确保在您的文档中声明了命名空间。

<html xmlns:xlink="http://www.w3.org/1999/xlink">

<!-- or if standalone svg -->

<svg xmlns:xlink="http://www.w3.org/1999/xlink">

但是,通过这种方式,我在 xhtml 文档中解决了相同的问题,这可能也适用于 html5 或独立的 SVG。

xlink 规范

祝你好运!

大多数 SVG 参数可以通过 setAttribute() 设置。 但是 setAttribute() 将无法分配标签的“xlink:href”...除非标签已经有一个 xlink:href。 所以最初,您必须使用 setAttributeNS()。 之后,正常的 setAttribute() 将起作用。 尽管如此,这表明 setAttributeNS() 是 SVG 更安全的选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM