繁体   English   中英

使用Javascript和字符串创建SVG片段

[英]Creating SVG fragments with Javascript and Strings

我已经看过几个关于如何使用DOM api从Javascript中创建SVG片段的例子,但我很好奇有什么我可以用来从类似于innerHTML的字符串创建一个SVG片段。 我试过这个:

var svg = '<foreignObject><body xmlns="http://www.w3.org/1999/xhtml"><p>Hello World</p></foreignObject>'
var range = document.createRange();
return range.createContextualFragment(svg);

问题是带有SVG的createContextualFragment()在Chrome中出现异常。 那么有一种跨浏览器的方式吗?

所以这就是我所做的:

parseXML('<foreignObject xmlns="http://www.w3.org/2000/svg"><body xmlns="http://www.w3.org/1999/xhtml"><p id="seriesTitle"></p><p id="seriesValue"></p><p style="margin:0;text-align:center;" id="seriesDate"></p></body></foreignObject>')

由于parseXml()不是完全跨浏览器支持,我在顶部有这个代码:

if (typeof parseXML=='undefined') {
    window.parseXML = function (s,doc) {
        doc = doc || document;
        var doc2=(new DOMParser()).parseFromString(s, "text/xml");
        return doc.adoptNode(doc2.documentElement);
    }
}

然后我可以使用jQuery来查询片段并设置我想要的值:

jQuery('#seriesTitle', detailChart.mytooltip).text( point.series.name );
jQuery('#seriesValue', detailChart.mytooltip).text( point.y );
jQuery('#seriesDate', detailChart.mytooltip).text( date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() );

问题是VML不支持foreignObject之类的东西。 SVG非常接近于构建不具备所有HTML头痛的应用程序的绝佳解决方案。

如果你想要innerHTML这样的东西,原始代码应该有范围选择元素,以设置正确的解析器上下文。 然后Chrome应该修复http://crbug.com/107982

假设错误已修复,这就是我将如何解析SVG片段。 https://github.com/pwnall/ddr/blob/master/javascripts/base/pwnvg.coffee#L184

与此同时,我提出了一个与你的解决方案非常相似的解决方案,但告诉DOMParser它正在处理SVG内容。 我认为你的解决方案对你的特定情况更好,但我的代码更接近innerHTML (实际上我的目标是匹配insertAdjacentHTML )。

https://github.com/pwnall/ddr/blob/master/javascripts/base/pwnvg.coffee#L169

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM