Jes*_* Vn 12 html javascript jquery svg dom
我正在尝试与Jquery和Svg一起工作.但我不想使用任何插件.
我现在要解决的问题是,当我尝试使用传统的追加模式将子项添加到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" );
Run Code Online (Sandbox Code Playgroud)
...但是在此操作之后,圆圈不会渲染.我检查至少圆圈是否真的附加到开发人员工具检查器中的DOM树,我发现两个元素都存在,具有先前设置的适当属性,但是使用jQuery创建的圆圈就好像它是一个html后代,而不是svg后裔.这意味着与svg circle元素相关的构造函数,原型和其他方法不是这个'jquery'圈子的一部分,而是与纯html标签相关.
有没有办法使用jquery创建svg元素作为svg后代,或者更好地使用纯javascript尽管生产力下降?
Dom*_*nic 12
一直无法尝试,但我打赌这会奏效.代替
$(mySvg).append("<circle />");
Run Code Online (Sandbox Code Playgroud)
做
$(mySvg).append(document.createElementNS("http://www.w3.org/2000/svg", "circle"));
Run Code Online (Sandbox Code Playgroud)
如果您计划不止一次这样做,也许
function svgEl(tagName) {
return document.createElementNS("http://www.w3.org/2000/svg", tagName);
}
$(mySvg).append(svgEl("circle"));
Run Code Online (Sandbox Code Playgroud)
这与通过$(document.createElement("div"))
代替获得更好性能的旧技巧相同$("<div />")
.
归档时间: |
|
查看次数: |
15385 次 |
最近记录: |