我有一个嵌入两个不同SVG文件的HTML文件,如下所示:
<html>
<body>
<object id="svg0" data="histograms.svg" type="image/svg+xml"></object>
<object id="svg1" data="test.svg" type="image/svg+xml"></object>
</body>
</html>
两个SVG文件都是交互式的,通过添加由onclick触发的javascript函数,如:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:ns1="http://www.w3.org/1999/xlink" height="172pt" version="1.1" viewBox="0 0 1209 172" width="1209pt">
<script type="text/ecmascript">
function choose(obj) {
var values = [0.08,0.77];
var names = [ "hist_1", "hist_2", "hist_3", "hist_4", "hist_5", "hist_6", "hist_7", "hist_8", "hist_9", "hist_10", "hist_11" ];
for ( var i=0; i<names.length; i++) {
var o = document.getElementById( names[i] );
o.style['opacity'] = values[0];
}
obj.style['opacity'] = values[1];
}
</script>
...
<g id="figure_1">
<g id="patch_1">
<path d=" M0 172.8 L1209.6 172.8 L1209.6 0 L0 0 z " style="fill:#ffffff;" />
</g>
<g id="axes_1">
<g cursor="pointer" id="hist_1" onclick="choose(this)">
<path d=" M20.835 70.52 L189.696 70.52 L189.696 12.96 L20.835 12.96 z " style="fill:#ffe6cc;" />
</g>
...
如何在其他SVG文件中点击一个SVG 文件触发javascript? (如果需要,可能通过顶级.html文件作为中间文件?)
答案 0 :(得分:2)
如果您在test.svg中编写代码,那么top会为您提供包含,所以
var svg0 = top.document.getElementById("svg0");
会从容器文档中获取对象元素。
然后
obj0Document = svg0.contentDocument;
if (obj0Document && obj0Document.defaultView)
obj0Window = obj0Document.defaultView;
else if (svg0.window)
obj0Window = svg0.window;
获取内容的文档和窗口。
访问SVG文档的“窗口”允许您访问SVG文档中脚本中定义的变量和函数。
e.g。 obj0Window.choose(something)
所有内容都必须具有相同的域才能发挥作用。