a.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%" version="1.1" xmlns="http://www.w3.org/2000/svg"> <g id="g"> <circle id="theCircle" cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/> <pc id="thePc"/> </g> </svg>
a.html内容如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script>
function dyn(){
var svgDoc = emb.getSVGDocument();
if(svgDoc == null) return;
var svgRoot = svgDoc.documentElement;
var cir = svgRoot.getElementById("theCircle");
//alert(cir.getAttribute("fill"));
cir.setAttribute('fill','cyan');
cir.onclick=function(){
cir.setAttribute("fill","green");
}
var thePc = svgRoot.getElementById("thePc");
var temp = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
//var temp = document.createElement("circle");
temp.setAttribute("cx","100");
temp.setAttribute("cy","100");
temp.setAttribute("r","40");
temp.setAttribute("stroke","black");
temp.setAttribute("stroke-width","2");
temp.setAttribute("fill","yellow");
svgRoot.getElementById("g").appendChild(temp);
}
</script>
</head>
<body onload="dyn()">
<embed id="emb" src="./a.svg" type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/" />
</body>
</html>
要注意:创建元素时候要
document.createElementNS(‘http://www.w3.org/2000/svg’, ‘circle’);
这么写,否则创建的是普通的DOM元素 不是SVG 的DOM元素,是不会显示在画面中的。