2016-05-12 108 views
2

我需要創建一個使用只有JavaScript這樣的結構:創建SVG元素通過JavaScript

<svg> 
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#circle"></use> 
</svg> 

但我有創造xmlns:xlink屬性的麻煩。這裏是我的js代碼:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); 
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); 
// throws error here 
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink'); 
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#circle'); 
svg.appendChild(use); 

如果我評論字符串設置xmlns:xlink所有工作良好,使SVG上面一樣,但沒有xmlns:xlink

我看到很多類似於我的問題,但他們沒有解決我的問題。

+0

@RobertLongson,我想這個,但我們如何設置'xmlns:xlink'屬性? – cassln

+0

@羅伯特朗鬆,哇,你說得對!現在所有的工作,看起來很好。你可以將你之前的評論格式化爲分享你知識的問題(它會更明顯)? – cassln

回答

1

關於

use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink'); 

你並不需要這一行,實際上它是無效的。

如果要在XML文檔中創建元素/屬性,並且在HTML中創建元素時不需要,則使用createElementNS創建元素或使用setAttributeNS創建屬性時會自動設置xml屬性文件。

0

這裏,我們去:

// "circle" may be any tag name 
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle"); 

// Set any attributes as desired 
shape.setAttribute("cx", 25); 
shape.setAttribute("cy", 25); 
shape.setAttribute("r", 20); 
shape.setAttribute("fill", "green"); 

// Add to a parent node; document.documentElement should be the root svg element. 
// Acquiring a parent element with document.getElementById() would be safest. 
document.documentElement.appendChild(shape); 
+0

我需要在不編輯HTML的情況下執行此操作。而創建圈子我也不需要。只需使用。 – cassln

+1

@cassln,我編輯了我的解決方案;) – praguan

+0

此代碼仍然與問題不匹配。 – cassln