使用jQuery创建和访问SVG标记? [英] Create and access SVG tag with jQuery?
问题描述
是否可以像这样在jQuery中创建一个SVG标记:
Is it possible to create an SVG tag in jQuery like so:
var dragSVG = $('<svg xmlns="http://www.w3.org/2000/svg"></svg>');
dragSVG.append('<rect x="0" y="0" width="20" height="20" style="fill:red"></rect>');
如果是这样,那么如何获得对DOM的访问权限?即。如果是HTML,我会执行以下操作:
And then if so, how does one get access to the DOM? ie. If it were HTML I'd do the following:
return dragSVG.html();
但由于它不是HTML,因此引发异常......或者我错过了一些完全基本的东西!?
But as it isn't HTML this throws an exception... Or am I missing something completely fundamental!?
编辑:
我会试着解释一下我的尝试更清楚地实现;我有一个代表SVG'项目'的按钮,可以将其拖到主SVG画布上。当用户开始拖动时,我想在鼠标下显示SVG项目以提供用户反馈。当用户将其放到画布上时,我需要将'item'移动到主画布上。
I'll try to explain what I'm try to achieve a bit more clearly; I have a button that represents an SVG 'item' that can be dragged onto a main SVG canvas. When the user starts dragging I want to display the SVG 'item' under the mouse to provide user-feedback. When the user drops this onto the canvas I need to move the 'item' onto the main canvas.
$('#testBtnDrag').draggable({
opacity: 0.7,
revert: 'invalid',
cursorAt: { top: 0, left: 0},
helper: function (event) {
var dragSVG = '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><rect x="0" y="0" width="20" height="20" style="fill:red"></rect></svg>';
return dragSVG;
}
});
// I can't attach the droppable to the SVG tag directly, IE / FF don't work with this
// so we have to attach it to a <div> tag that wraps the <svg>.
$('#drawArea').droppable({
accept: '.svg-item',
drop: function (event, ui) {
// Get the mouse offset relative to the <svg> canvas
var posX = event.originalEvent.clientX - $(this).offset().left;
var posY = event.originalEvent.clientY - $(this).offset().top;
// Get the dragged element and put it onto the "main" canvas
var rawSVG = ui.helper.children().html() // This won't work!
var mainCanvas = $('#drawArea > svg');
mainCanvas.append(rawSVG);
}
});
});
推荐答案
SVG本质上是一种XML文件格式。请尝试 parseXML()。如果这不起作用,请尝试
http://keith-wood.name/svggraphRef.html 。
SVG is essentially an XML file format. Try parseXML() instead. If this doesn't work try http://keith-wood.name/svggraphRef.html.
这篇关于使用jQuery创建和访问SVG标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!