【问题标题】:SVG symbols do not fire onload event (only in firefox). I look for a workaroundSVG 符号不会触发 onload 事件(仅在 firefox 中)。我正在寻找解决方法
【发布时间】:2016-06-22 02:24:41
【问题描述】:

我正在一个项目中使用 D3.js 来制作带有 SVG 的图表。该图使用 SVG 符号。我有 javascript 代码来管理这些带有 onload 事件的项目。

在诸如 webkit 引擎之类的浏览器中运行得非常好。但是 Firefox...Firefox 不会在 SVG 中运行任何 onload 事件。

嗯,我看到了这个错误,并认为 Firefox 是免费软件,这些人喜欢错误跟踪。我已经上传了错误https://bugzilla.mozilla.org/show_bug.cgi?id=1254159

而这些人的反应是“WONTFIX”。

检查bug的例子很小很清楚:

<html>
    <head>
        <title>test onload event in a svg symbol</title>
        <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" pointer-events="all" width="500px" height="500px" style="background: #ffff00;">
            <g class="cat" transform="translate(100 100)">
                <use xlink:href="animals.svg#cat" onload="javascript: console.log('This message is not showed in firefox.');" />
            </g>
        </svg>
        <script type="text/javascript">
            d3.select("svg")
                .append("g")
                    .attr("class", "dog")
                    .attr("transform", "translate(200 200) scale(0.5)")
                    .append("use")
                        .attr("xlink:href", "animals.svg#dog")
                        .on("load", function() {
                            console.log("And this message is not showed in firefox too.");
                        });
        </script>
    </body>
</html>

最后,我在w3c文档中查找,符号中的事件onload是标准的:https://www.w3.org/TR/SVG/struct.html#UseElement

有没有人解决这个问题?

【问题讨论】:

  • 把你的代码放在外部&lt;svg&gt;元素的SVGLoad事件中。
  • 但是 SVG 已加载,并且 javascript 会动态添加其他符号,例如通过 javascript 将图像添加到网络中。正如您在代码中的第二个示例中看到的那样。
  • 然后让 animals.svg 文件在其加载事件中调用父 html 文件中的某个函数。

标签: javascript firefox d3.js svg


【解决方案1】:

解决这个问题的一个很长的方法是自己处理外部资源的加载(或者更确切地说,在 d3 的帮助下)。

D3有xml加载器功能(https://github.com/mbostock/d3/wiki/Requests#d3_xml),svg是xml,所以可以做如下操作:

  • 准备不使用外部资源的内容
  • 使用 d3 加载 svg
  • 在 d3.xml 的回调函数中,您会得到一个 DOML 元素:将其插入到图形中的相关位置,然后执行您在“onload”事件中将执行的任何工作。

(可能有更简单的方法,我只是不知道)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2016-10-21
    • 1970-01-01
    • 2015-10-26
    • 2011-12-22
    • 2012-12-04
    相关资源
    最近更新 更多