【发布时间】:2011-09-03 04:19:49
【问题描述】:
我正在尝试将 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" );
...但是在这个动作之后,圆圈没有渲染。我在 Developers Tool Inspector 中检查了至少该圆圈是否真的附加到了 DOM 树中,我发现这两个元素都存在,并且之前设置了正确的属性,但是使用 jQuery 创建的圆圈就好像它是一个 html 后代,而不是 svg 的后代。这意味着与 svg circle 元素相关的构造函数、原型和其他方法不是 this 'jquery' circle 的一部分,而是与纯 html 标记相关。
有没有办法使用 jquery 将 svg 元素创建为 svg 后代,还是使用纯 JavaScript 更好?
【问题讨论】:
-
>我正在尝试将 Jquery 和 Svg 一起使用。但我不想使用任何插件。 - 你能描述一下原因吗?现有的插件和库都有很好的文档、示例、结构......例如,看看keith-wood.name/svg.html。
-
你知道
.attr()可以接受一个带有键值对的JavaScript 对象吗?例如。你可以做$(mySvg).find("circle").attr({ cx: 160, cy: 70, r: 30, "class": "class1" }); -
不是跨浏览器的问题,因为我在几个浏览器中测试过。
标签: javascript jquery html dom svg