在HTML5中使用JS创建内联SVG [英] Creating inline SVG with JS in HTML5

查看:101
本文介绍了在HTML5中使用JS创建内联SVG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用本地HTML5文件 - 它顶部有<!DOCTYPE html> 。我把这样的东西放进去了:

I'm working with a local HTML5 file -- it's got <!DOCTYPE html> at the top. I put something like this in it:

<svg height="2em" width="3em" preserveAspectRatio="none" viewBox="0 0 100 100">
  <rect x="0" y="0" width="100" height="100" fill="red"/>
</svg>

(没有名称空间,非常感谢HTML5!),它在Chrome和FF4测试版中表现出色。

(no namespaces, thanks HTML5!), and it displays great in Chrome and FF4 beta.

现在我想通过JS创建相同的东西。我正在使用Prototype,所以我写了类似的东西:

Now I want to create the same thing but via JS. I'm using Prototype, so I wrote something like:

var box = new Element('svg', {'width':'3em', 'height':'2em', 'preserveAspectRatio': 'none', 'viewBox': '0 0 100 100'});
box.appendChild(new Element('rect', {fill:'red', x:'0', y:'0', width:'100', height:'100' }));
container.appendChild(box);

我可以在Firebug / DOM检查器(FF和Chrome)中看到它正在创建相同的DOM结构为此。

I can see in Firebug / DOM inspector (both FF and Chrome) that it's creating the same DOM structure for this.

我看到的唯一区别是属性(preserveAspectRatio和viewBox)都是小写的,但我尝试在第一次更改属性测试(静态HTML)到全小写,它仍然可以正常工作,所以我不认为这是问题。

The only difference I see is that the attributes ("preserveAspectRatio" and "viewBox") are all-lowercase, but I tried changing the attributes in my first test (static HTML) to all-lower-case and it still works fine, so I don't think that's the problem.

HTML5 SVG功能是否仅限于静态HTML,我还需要通过JS添加SVG内容的命名空间,还是我还缺少其他东西?

Is the HTML5 SVG capability limited to static HTML, and I need to do namespaces still for adding SVG content via JS, or is there something else I'm missing?

推荐答案


原来这是一个命名空间问题:需要使用createElementNS(http://www.w3.org/2000/svg,...)创建元素,Prototype碰巧没有内置(新元素(...))支持。所以我猜HTML5 SVG的情况基本上是没有命名空间的SVG在解析过程中会添加名称空间(但之后它就像之前的XHTML一样)。

Turns out it was a namespace issue: the elements need to be created with createElementNS("http://www.w3.org/2000/svg", ...), which Prototype happens to have no built in (new Element(...)) support for. So I guess the HTML5 SVG situation is basically "SVG without a namespace gets the namespace added during parsing (but after that it's just like XHTML before)".

PS,今天回答您的问题按钮对我来说不起作用,所以如果有人将此作为答案添加,我会将其标记为正确。 : - )

P.S., the "Answer Your Question" button here isn't working for me today, so if anybody adds this as as answer, I'll mark it correct. :-)

这篇关于在HTML5中使用JS创建内联SVG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆