2013-05-18 38 views
1

我想要做的是從HTML中的Javascript代碼動態地在嵌入式SVG文檔中設置JavaScript腳本引用。如何在SVG中獲得工作的動態javascript參考

我認爲這與將節點動態附加到嵌入式SVG文檔中的適當位置一樣簡單。

我發現該節點實際上是在運行時添加的(可以使用Firefox Inspect Element進行檢查),但引用中包含的Javascript代碼在需要時不會執行。

有人對此有個想法嗎?爲了讓SVG能夠在Javascript代碼中調用函數,還需要做其他事情嗎?

這裏是一個簡化的情景:

的test.html(嵌入SVG)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<script type="text/javascript"> 
    function ActivateScript() { 
     var svgdoc = document.getElementById("svg"); 
     var newref = svgdoc.contentDocument.createElement('script'); 
     newref.setAttribute("type", "text/javascript"); 
     newref.setAttribute("xlink:href", "script.js"); 
     svgdoc.contentDocument.documentElement.appendChild(newref); 
    } 
</script> 
</head> 
<body> 
<input type="button" value="Activate script" onclick="ActivateScript()" /> 
<object id="svg" type="image/svg+xml" data="embed.svg"/> 
</body> 
</html> 

embed.svg

<?xml version="1.0"?> 
<svg xmlns="http://www.w3.org/2000/svg" width="12cm" height="12cm" xmlns:xlink="http://www.w3.org/1999/xlink"> 
<g style="fill-opacity:1; stroke:black; stroke-width:0.1cm;"> 
<circle cx="6cm" cy="2cm" r="100" style="fill:red;" transform="translate(0,50)" onclick="MyFunction()"/> 
</g> 
</svg> 

最後是外部JavaScript我想動態分配(script.js)

function MyFunction() { 
alert("I can execute script!"); 
} 

回答

2

SVG元素必須在SVG命名空間是http://www.w3.org/2000/svg所以不是的createElement的,所以你需要

var newref = svgdoc.contentDocument.createElementNS('http://www.w3.org/2000/svg', 'script'); 
    newref.setAttribute("type", "text/javascript"); 
    newref.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "script.js"); 
+0

大,必須使用同樣的createElementNS的XLink的屬性,它必須在XLink命名空間去創造!這就是訣竅!非常感謝羅伯特! – Optavius

相關問題