首先在index.html中引入了tuoyuan.svg:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
</head>
<body>
<embed src="tuoyuan.svg" width="500" height="300" type="image/svg+xml"
pluginspage="http://www.adobe.com/svg/viewer/install/" id="em"/>
<button onclick="change()">改变椭圆水平半径</button>
</body>
<script>
function change(){
var embedEle=document.getElementById("em");
console.log(embedEle);
var svg=embedEle.getSVGDocument();
console.log(svg);
var svgdoc=svg.documentElement;
console.log(svgdoc);
var tuoyuan=svgdoc.getElementsByTagName("ellipse")[0];
tuoyuan.setAttribute("rx","100");
}
</script>
</html>
tuoyuan.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">
<ellipse cx="300" cy="150" rx="200" ry="80"
style="fill:rgb(200,100,50);stroke:rgb(0,0,100);stroke-width:2"/>
</svg>
默认显示效果:
点击按钮之后:
可以看到使用JavaScript是可以操作引入的svg文档的,其实这也很好理解,本来你embed就是html中的一个标签,我获取到embed是完全没有问题的,通过embed标签再获取到svg文档对象,svg文档对象其实就是一个xml文件,JavaScript操作xml文件我们知道是遵从dom标准的。documentElement属性在这里是返回的svg的根标签,而不是html里面返回的html。