将onclick事件从嵌入的SVG路由到更高级别

Routing onclick event from embedded SVG to higher level

本文关键字:路由 SVG 高级别 onclick 事件      更新时间:2023-09-26

我有一个HTML文件,它嵌入了两个不同的SVG文件,如下所示:

<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>

通过添加由onclick触发的javascript函数,这两个SVG文件都是交互式的,比如:

<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&lt;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文件作为中间文件?)

如果您在test.svg中编写代码,那么top会为您提供containiner,因此

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文档中脚本中定义的变量和函数。

例如obj0Window.choose(something)

所有东西都必须有相同的域才能工作。