SVG嵌入到HTML中,拖放代码问题

SVG embedded into HTML, drag and drop code issues

本文关键字:拖放 代码 问题 HTML SVG      更新时间:2023-09-26

我有一个嵌入到HTML文档中的SVG文件。我可以用javascript使用id和类访问html和svg中的元素。但是,我想对嵌入的svg执行一些拖放操作。我一直在http://svg-whiz.com/svg/DragAndDrop.svg上使用以下示例将SVG从javascript中分离出来,但是当我将SVG嵌入HTML中时,它会给我带来麻烦。当嵌入

时,SVG中的init函数不起作用。
onload="initSVG(evt)"

我需要访问HTML中SVG的根,这样我才能使拖放例程工作。独立svg的原始代码如下所示:

function initSVG(evt)
{
SVGDocument = evt.target.ownerDocument;
SVGRoot = SVGDocument.documentElement;
TrueCoords = SVGRoot.createSVGPoint();
GrabPoint = SVGRoot.createSVGPoint();
}

我的重写是这样的,这样它就可以在没有onload事件调用的情况下运行:

function initSVG()
{
SVGRoot = document.getElementsByTagName("svg");
TrueCoords = SVGRoot.createSVGPoint();
GrabPoint = SVGRoot.createSVGPoint();
}

这给出了错误:"对象#没有方法'CreateSVGPoint'"。因此,它似乎没有像对待独立的SVG那样对待导入的SVG。我如何获得svroot ?

谢谢!

注:我知道我可能应该使用jquery,但我想学习原始DOM。

getElementsByTagName函数返回一个NodeList,而不是一个元素。试一试:

SVGRoot = document.getElementsByTagName("svg")[0];