看起來這樣做的「正確」方法實際上是使用SVG「use」元素,而不是圖像。原因是SVG use元素的DOM接口指定了一個屬性「instanceRoot」,它允許您獲取與該使用元素對應的「實例樹」的根:http://www.w3.org/TR/SVG/struct.html#InterfaceSVGUseElement
因此,您將結束了,看起來像下面這樣的解決方案: circle.svg:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="4in" height="4in" id="the_svg"
viewBox="0 0 4 4" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle r="1" fill="blue" stroke="none" id="the_circle"/>
</svg>
文件,它使用circle.svg的SVG根節點:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" id="foo"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<use xlink:href="circle.svg#the_svg"/>
</svg>
但不幸的是,儘管Firefox支持ü se的使用元素與外部文件,目前Webkit中有一個不允許這樣的錯誤:https://bugs.webkit.org/show_bug.cgi?id=12499
此外,Firefox似乎沒有實現使用元素的instanceRoot屬性。
因此,看起來您可能需要解決當前SVG實施的限制。我建議這樣做的方式是使用XMLHttpRequest下載您想要鏈接的文檔,並將下載的文檔的DOM導入到主機文檔的DOM中。下面的代碼實現這一點,在Firefox,Opera和鉻工作:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" id="foo"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<script>
function fetchXML (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function (evt) {
//Do not explicitly handle errors, those should be
//visible via console output in the browser.
if (xhr.readyState === 4) {
callback(xhr.responseXML);
}
};
xhr.send(null);
};
//fetch the document
fetchXML("http://localhost:8082/tmp/circle.svg",function(newSVGDoc){
//import it into the current DOM
var n = document.importNode(newSVGDoc.documentElement,true);
document.documentElement.appendChild(n);
var circle = document.getElementById("the_circle"); //now you have the circle
})
</script>
</svg>
發佈在SVG-開發商http://tech.groups.yahoo.com/group/svg-developers/message/63940 – rodrigob 2010-07-29 14:50:18