簡體   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