是否可以使用JavaScript处理嵌入HTML文档中的SVG文档?
时间:2020-03-06 14:46:19 来源:igfitidea点击:
我制作了一个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文档上的document变量。可以添加任何添加到其中的方法。
几年前,我被要求使用SVG创建一个基于Ajax的2人游戏。它可能不完全是我们要寻找的解决方案,但可以侦听SVG中的事件。这是SVG控制器:
仅供参考,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,但这是它的要旨。
我已经通过JavaScript探索了svg。请参阅博客:使用JavaScript缩放SVG图形
我认为David Dailey博士是我们会发现的最出色的SVG / JS信息
http://srufaculty.sru.edu/david.dailey/svg/
另请参阅jQuery SVG插件
要获得IE6的支持,请查看SVGWeb。
该库随附的示例代码中提供了有关如何使用JavaScript操纵SVG的示例。
邮件列表的存档中也有大量信息。

