被接受的答案显示的方法过于复杂。正如Forresto在他的回答中所说,"它似乎将它们添加到DOM资源管理器中,但不会在屏幕上显示",原因是html和svg具有不同的命名空间。
最简单的解决方法是“刷新”整个svg。在附加圆形(或其他元素)之后,请使用以下内容:
$("body").html($("body").html());
这样做就可以了。圆形出现在屏幕上。
或者,如果你想的话,使用一个容器div:
$("#cont").html($("#cont").html());
将您的SVG包装在容器div内:
<div id="cont">
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
</svg>
</div>
The functional example:
http://jsbin.com/ejifab/1/edit
This technique has the following advantages:
- You can edit existing SVG (that is already in DOM), for example, created using Raphael or like in your example "hard coded" without scripting.
- You can add complex element structures as strings, for example, $('svg').prepend('<defs><marker></marker><mask></mask></defs>') like you do in jQuery.
- After the elements are appended and made visible on the screen using $("#cont").html($("#cont").html()), their attributes can be edited using jQuery.
编辑:
上述技术仅适用于“硬编码”或DOM操作(= document.createElementNS等)的SVG。如果使用Raphael创建元素,则(根据我的测试),如果使用 $(“#cont”).html($(“#cont”).html());
,则Raphael对象与SVG DOM之间的链接将中断。解决此问题的方法是根本不使用 $(“#cont”).html($(“#cont”).html());
,而是使用虚拟SVG文档。
这个虚拟SVG首先是SVG文档的文本表示形式,只包含所需的元素。例如,如果我们想向Raphael文档添加一个过滤器元素,那么虚拟文档可能是这样的<svg id="dummy" style="display:none"><defs><filter><!-- Filter definitons --></filter></defs></svg>
。首先使用jQuery的$(“body”)。append()方法将文本表示转换为DOM。当(过滤器)元素在DOM中时,可以使用标准的jQuery方法查询并附加到由Raphael创建的主SVG文档中。
为什么需要这个虚拟元素?为什么不能严格地将过滤器元素添加到 Raphael 创建的文档中?如果你尝试使用如下代码
$("svg").append("<circle ... />")
,它会被创建为 html 元素,并且没有任何屏幕上的显示,正如答案所描述的那样。但是,如果整个 SVG 文档被附加,则浏览器会自动处理 SVG 文档中所有元素的命名空间转换。
以下示例介绍了该技术:
var p = Raphael("cont", 200, 200);
$(p.canvas).attr("id","p");
var f = '<filter id="myfilter"><!-- filter definitions --></filter>';
$("body").append('<svg id="dummy" style="display:none"><defs>' + f + '</defs></svg>');
$("#p defs").append($("#dummy filter"));
$("#dummy").remove();
var r = p.rect(10,10,100,100);
$(r.node).attr("filter","url(#myfilter)");
这种技术的完整演示在这里:http://jsbin.com/ilinan/1/edit。
(我还不知道为什么在使用Raphael时 $(“#cont”).html($(“#cont”).html()); 不起作用。 这将是非常简短的黑客。)
d3.select('body').append('svg').attr('width','100%');
- chharvey$.parseXML
方法。 - bobince