是否可以直接使用jquery和Svg(没有插件)?
I'm trying to work with Jquery and Svg together. But I don´t want to use any plugin.
我正在尝试与Jquery和Svg一起工作。但我不想使用任何插件。
The problem I am dealing now is that when I try to work using the traditional append mode to add a child to the svg document, the object is not rendered. Let´s check out what I tried to do:
我现在要解决的问题是,当我尝试使用传统的追加模式将子项添加到svg文档时,该对象不会被渲染。让我们看一下我尝试做的事情:
/* Creating the svg container using pure JS */
var container = document.getElementById("svg_space");
mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
mySvg.setAttribute("version", "1.2");
mySvg.setAttribute("baseProfile", "tiny");
container.appendChild(mySvg);
/* Adding a child and setting attributes to the SVG container using pure JS */
Circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
Circle.setAttribute("cx", "60");
Circle.setAttribute("cy", "30");
Circle.setAttribute("r", "13");
Circle.setAttribute("class", "class1");
mySvg.appendChild(Circle); /* After this, the circle is rendered */
/* Then, I tried to use jQuery to perform the same action... */
$(mySvg).append("<circle />");
$(mySvg).find("circle").attr("cx","160");
$(mySvg).find("circle").attr("cy","70");
$(mySvg).find("circle").attr("r","30");
$(mySvg).find("circle").attr("class","class1" );
...but after this action, the circle does not render. I check if at least the circle was really appended to the DOM tree in the Developers Tool Inspector, and I found out that both element exist, with the proper attributes previously set, but the circle created with jQuery was as if it were a html descendant, not as a svg descendant. This means that the constructors, prototypes and other methods related to a svg circle element was not part of the this 'jquery' circle, but instead the related to a pure html tag.
...但是在此操作之后,圆圈不会渲染。我检查至少圆圈是否真的附加到开发人员工具检查器中的DOM树中,我发现两个元素都存在,具有先前设置的正确属性,但是使用jQuery创建的圆圈就好像它是一个html后代而不是作为svg后裔。这意味着与svg circle元素相关的构造函数,原型和其他方法不是这个'jquery'圈子的一部分,而是与纯html标签相关。
Is there a way to create svg elements as svg descendants using jquery, or is better the use of pure javascript despite the loss of productivity?
有没有办法使用jquery创建svg元素作为svg后代,或者更好地使用纯javascript尽管生产力下降?
3 个解决方案
#1
11
Haven't been able to try, but I bet this would work. Instead of
一直无法尝试,但我打赌这会奏效。代替
$(mySvg).append("<circle />");
Do
$(mySvg).append(document.createElementNS("http://www.w3.org/2000/svg", "circle"));
If you plan on doing this more than once, maybe
如果您计划不止一次这样做,也许
function svgEl(tagName) {
return document.createElementNS("http://www.w3.org/2000/svg", tagName);
}
$(mySvg).append(svgEl("circle"));
This is the same as the old trick of getting better performance via $(document.createElement("div"))
instead of $("<div />")
.
这与通过$(document.createElement(“div”))而不是$(“
更多相关文章
- 如何使用CSS消除元素的偏移?
- KeyPress或KeyDown事件没有得到html元素的buind
- 行内元素与块级元素
- 固定定位,父元素具有转换
- 在c#中获取html元素的实际边距
- 两个堆叠的元素与他们旁边的元素成比例增长
- html css伪元素标签(二)灵活
- 如何使用Watir访问自定义属性的元素?
- HTML5按钮元素新属性formaction,formenctype等简介