2008-09-26 127 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> 
    
相關問題