使用 Javascript 和字符串创建 SVG 片段
我已经看到了几个关于如何使用 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 中出现异常。那么有没有跨浏览器的方法来做到这一点?
I've seen several examples about how to use the DOM api to create SVG fragments from within Javascript, but I'm curious is there something I can use to create a SVG fragment from a string similar to innerHTML. I've tried this following:
var svg = '<foreignObject><body xmlns="http://www.w3.org/1999/xhtml"><p>Hello World</p></foreignObject>'
var range = document.createRange();
return range.createContextualFragment(svg);
Problem is createContextualFragment() with SVG blows up with an exception in Chrome. So is there a cross browser way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以这就是我所做的:
由于 parseXml() 并不完全支持跨浏览器,因此我在顶部有以下代码:
然后我可以使用 jQuery 来查询而不是片段并设置我想要的值:
问题是 VML 不支持不支持foreignObject之类的东西。 SVG 非常接近于成为构建应用程序的绝佳解决方案,而无需担心所有 HTML 问题。
So here is what I did:
Since parseXml() isn't exactly cross browser supported I have this code at the top:
Then I can use jQuery to query instead the fragment and set the values I'd like:
Problem is VML doesn't support anything like foreignObject. SVG is so close to being a great solution for building applications that doesn't have all the HTML headaches.
如果您想要像
innerHTML
这样的东西,您的原始代码应该具有选择元素的范围,以设置正确的解析器上下文。然后 Chrome 应该修复 http://crbug.com/107982假设 bug 已修复,以下是我将如何解析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
If you want something like
innerHTML
, your original code should have the range select the element, to set up the right parser context. Then Chrome should fix http://crbug.com/107982Assuming the bug was fixed, here's how I would parse a SVG fragment.
https://github.com/pwnall/ddr/blob/master/javascripts/base/pwnvg.coffee#L184
In the meantime, I came up with a solution that is very similar to yours, but tells
DOMParser
that it's dealing with SVG contents. I think your solution is better for your specific case, but my code is a bit closer toinnerHTML
(actually I aim to matchinsertAdjacentHTML
).https://github.com/pwnall/ddr/blob/master/javascripts/base/pwnvg.coffee#L169