【问题标题】:How to call a function in the parent html document from an embedded svg如何从嵌入式 svg 调用父 html 文档中的函数
【发布时间】:2012-05-16 03:31:31
【问题描述】:

我对 svg 很陌生,我必须用它来完成一项任务,但我遇到了很多麻烦。

我有一个 svg(例如地图),其区域由路径定义。

我的目标是触发 svg 外部的 onClick 函数来做一些事情(例如,通过 ajax 检索与所选区域相关的一些人员数据,并将它们显示在 html 页面中的 svg 之外)。

我不能做的是从 svg 中的元素触发在 svg 之外定义的函数。

如果我添加 svg 内联,我可以做到这一点,但我需要使用 embed 标记使其与 ie Adob​​e 插件一起使用。有什么建议吗?提前致谢。

【问题讨论】:

  • 如果 JavaScript 通过 <embed><img> 或类似方式嵌入,则无法从 SVG 执行 JavaScript。
  • …但是 jQuery 不是为处理 SVG 而设计的。
  • 您可能想要查看的是一个库,例如raphaeljs.com
  • 不幸的是,svg 太复杂了,我在用 raphael 处理它时遇到了问题。没有解决方法来实现目标?
  • 您可以直接使用 DOM 或使用 d3.js 之类的东西。如果你正确加载它,Raphael 也应该可以工作。

标签: javascript svg jquery-svg


【解决方案1】:

this example

svg 中的代码如下所示:

    document.getElementById("svgroot").addEventListener("click", 
                                                        sendClickToParentDocument,
                                                        false);

    function sendClickToParentDocument(evt)
    {
        // SVGElementInstance objects aren't normal DOM nodes, 
        // so fetch the corresponding 'use' element instead
        var target = evt.target;
        if(target.correspondingUseElement)
            target = target.correspondingUseElement;

        // call a method in the parent document if it exists
        if (window.parent.svgElementClicked)
            window.parent.svgElementClicked(target);
        else
            alert("You clicked '" + target.id + "' which is a " + target.nodeName + " element");
    }

在父文档中,您有一个脚本,其中包含您要调用的函数,例如:

function svgElementClicked(theElement)
{
    var s = document.getElementById("status");
    s.textContent = "A <" + theElement.nodeName + 
        "> element with id '" + theElement.id + 
        "' was clicked inside the <" + 
        theElement.ownerDocument.defaultView.frameElement.nodeName.toLowerCase() + 
        "> element.";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多