【发布时间】:2017-02-13 20:06:02
【问题描述】:
我正在尝试在 HTML4 文档中内联 SVG。有人建议我可能有一些问题,因为 HTML4 不支持内联 SVG,所以我应该用 XHTML 代替。
有趣的是,虽然支持内联 SVG 不是 HTML4 标准的一部分,但使用 WebKit 的浏览器应该对内联 SVG 感到满意,因为它的解析器能够解析 HTML5,而 HTML5 完全支持内联 SVG。不幸的是,Firefox 不在同一个联盟中。
但是,如果我在运行时使用 JavaScript 将 SVG 节点附加到容器中,FF 也可以(见下文。我从 jquery svg 中得到了这个想法,一个插件- 用于 jquery)。 为什么可以这样做? 在我看来这太好了,难以置信。 (我是 JavaScript 编程的完全新手,可能遗漏了一些非常明显的东西......)
function onloadSVG(div_container) {
var svgE = document.createElementNS('http://www.w3.org/2000/svg',
'svg');
svgE.setAttribute('version', '1.1');
svgE.setAttribute('width', div_container.clientWidth);
svgE.setAttribute('height', div_container.clientHeight);
div_container.appendChild(svgE);
var node = svgE.ownerDocument.createElementNS('http://www.w3.org/2000/svg',
'circle');
node.setAttribute('cx', '100');
node.setAttribute('cy', '100');
node.setAttribute('r', '50');
node.setAttribute('fill', 'red');
node.setAttribute('stroke', 'black');
node.setAttribute('stroke-width', '5');
svgE.appendChild(node);
}
【问题讨论】:
-
请问:为什么不直接输入SVG in XHTML?它在所有支持 SVG 的浏览器中都能正常工作,并且不需要 JS hack。
-
感谢您的建议,但我做不到。我正在为实验语言开发一个库。到目前为止,它只生成 HTML。
标签: javascript jquery html svg