javascript - 在 HTML5 中使用 JS 创建内联 SVG

标签 javascript html svg

我正在处理一个本地 HTML5 文件——它有 <!DOCTYPE html>在顶部。我在里面放了这样的东西:

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

(没有 namespace ,感谢 HTML5!),它在 Chrome 和 FF4 测试版中显示效果很好。

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

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 结构。

我看到的唯一区别是属性(“preserveAspectRatio”和“viewBox”)是全小写的,但我尝试将我的第一个测试(静态 HTML)中的属性更改为全小写,但它仍然有效很好,所以我认为这不是问题所在。

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

最佳答案

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)".

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. :-)

关于javascript - 在 HTML5 中使用 JS 创建内联 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4116606/

相关文章:

javascript - 是否有检查嵌套属性是否存在的快捷方式

javascript - 如何调用 html 元素的触发器更改事件

javascript - 根据鼠标位置旋转 SVG 渐变

javascript - 将内联 SVG 保存为 JPEG/PNG/SVG

javascript - jQuery 无法在外部 javascript 文件中工作

javascript - 如何在指令中获取 {{text}}?

html - 列表样式类型左对齐

html - 使用伪类作为普通类

css - 如何为具有自定义列宽的可滚动表格完成固定标题?

javascript - 文本元素未显示在 SVG 上