2008-09-26 71 views
18

我做了一个SVG图像,或者更像迷你应用程序,用于查看数据图。我想将它包含在HTML页面中,并调用SVG图像上的方法。是否可以使用JavaScript处理HTML文档中嵌入的SVG文档?

例子:

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

是它在所有可能的呼吁SVG文件的方法呢?如果是这样,我该如何声明在SVG文件中公开的方法,以及如何从HTML文档调用它们?

回答

10

解决方案:

在SVG:

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

在HTML(使用原型添加事件侦听器):

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

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

3

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

仅供参考,SVG正在拖放(这是西洋陆军棋)

/****************** 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的,但是这是它的要点。

0

对于IE6的支持,看看SVGWeb

有一些关于如何在随库提供的示例代码中使用JavaScript处理SVG的示例。

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

5

事情实际上比你期望的要简单。你并不需要阅读令人费解的教程来理解概念,你也不需要使用JQuery。以下是基本布局:

  • 您的html文档中的JavaScript函数。

    <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> 
    
相关问题