我想修改下amchart的饼图样式,动态创建svg中的text标签,但是在chrome中测试
var $el = $('<text y="-10" fill="#d10000" font-family="Verdana" font-size="20" text-anchor="start" transform="translate(389,269)" fuck-amchart="0">24.4%</text>');
$($0).after($el);
这样的代码是无法生效的,而只有这样的可以:
$el = $($0).clone();
$el.attr('font-size', 32);
$($0).after($el);
也就是说,用jquery创建的元素,是无法写入svg的,只能从svg中现有元素复制出来,然后修改的元素可以追加到svg中。
今天查了下,看到这个讨论, http://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element
When you pass a markup string into $, it’s parsed as HTML using the browser’s innerHTML property on a (or other suitable container for special cases like ). innerHTML can’t parse SVG or other non-HTML content, and even if it could it wouldn’t be able to tell that was supposed to be in the SVG namespace.
innerHTML is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn’t give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn’t designed for use with SVG at all and many operations may fail.
HTML5 promises to let you use without an xmlns inside a plain HTML (text/html) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you’ll not be able to use innerHTML even though they look like part of an HTML document.
However, for today’s browsers you must use XHTML (properly served as application/xhtml+xml; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you’d have to escape the < symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns declaration. example:
意思是$方法创建的是html元素,会被当作html元素解析,所以一个hack办法就是,动态创建个
<script type="text/javascript"><![CDATA[
function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}
document.getElementById('s').appendChild(parseSVG(
'<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
));
]]></script>