我已经做了一个SVG图像,或者更像是小型应用程序,用于查看的图表数据。我希望包括这一HTML网页,并呼吁方法的SVG图像。

例如:

<object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>

它是在所有可以调用的方法上的SVG文件?如果是这样,我怎么声明的方法来获得在SVG文件,以及如何做的,我叫他们从HTML文档?

有帮助吗?

解决方案

解决方案:

在svg:

<script>document.method = function() {}</script>

在html中(使用原型来添加事件监听器):

<script>$("img").observe("load", function() {$("img").contentDocument.method()});

您需要侦听图像上的加载事件。加载图像后,可以使用 element.contentDocument 访问svg文档上的文档变量。添加到其中的任何方法都将可用。

其他提示

事情实际上是简单的比你的期望。你真的不需要读令人费解的教程以理解的概念,既没有做你必须使用的!这里是基本布局:

  • JavaScript功能在你html文档。

    <script type="text/javascript">
    function change(){
        var s=document.getElementById("cube");
        s.setAttribute("stroke","0000FF");
    }
    </script>
    
  • SVG元,我们正在试图操纵。

    <svg width=100 height=100 style='float: left;'>
      <rect x="10" y="10" width="60" height="60" id="cube" onclick="change()" stroke=#F53F0C stroke-width=10 fill=#F5C60C />
    </svg>
    
  • 一个内联键,将触发的变化。请注意,在我的例的事件也会触发,通过点击魔方本身。

    <button onclick="change()">Click</button>
    

几年前,我被要求使用SVG创建一个基于Ajax的双人游戏。它可能不是您正在寻找的解决方案,但它可以帮助您监听SVG中的事件。这是SVG控制器:

fyi,SVG被拖放(这是Stratego)

/****************** Track and handle SVG object movement *************/
var svgDoc;
var svgRoot;
var mover='';       //keeps track of what I'm dragging

///start function////
//do this onload
function start(evt){
    //set up the svg document elements
    svgDoc=evt.target.ownerDocument;
    svgRoot=svgDoc.documentElement;
    //add the mousemove event to the whole thing
    svgRoot.addEventListener('mousemove',go,false);
    //do this when the mouse is released
    svgRoot.addEventListener('mouseup',releaseMouse,false); 
}

// set the id of the target to drag
function setMove(id){ mover=id; }

// clear the id of the dragging object
function releaseMouse(){ 
    if(allowMoves == true){ sendMove(mover); }
    mover=''; 
}

// this is launched every mousemove on the doc
// if we are dragging something, move it
function go(evt){
    if(mover != '' && allowMoves != false) {
        //init it
        var me=document.getElementById(mover);

        //actually change the location
        moveX = evt.clientX-135; //css positioning minus 1/2 the width of the piece
        moveY = evt.clientY-65;
        me.setAttributeNS(null, 'x', evt.clientX-135);
        me.setAttributeNS(null, 'y', evt.clientY-65);
    }
}

function moveThis(pieceID, x, y) {
    $(pieceID).setAttributeNS(null, 'x', x);
    $(pieceID).setAttributeNS(null, 'y', y);
}

我的应用程序是纯粹的SVG + JavaScript,但这是它的要点。

我会引用David Dailey博士作为你会发现的最棒的SVG / JS信息 http://srufaculty.sru.edu/david.dailey/svg/

我已经通过JavaScripts探索了svg。请参阅博客:使用JavaScripts扩展SVG图形

另请参阅 jQuery SVG插件

要获得IE6的支持,请查看 SVGWeb

有关如何使用随库提供的示例代码中的JavaScript操作SVG的示例。

邮件列表的档案中也有相当多的信息。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top