HTML5 中的动态 SVG



我希望SVG节点在html5中是一等公民,但我得到了一个意外的行为(在Firefox 55.0.2和Chrome 54.0.2840.71下(。

在下面的 html 文件中,我希望将一个大圆圈动态添加到新创建的 svg 元素中。相反:

  • 检查器告诉我 DOM 被正确修改了
  • 不显示任何内容
  • 当我将 DOM(复制 -> 外部 HTML,脚本删除(复制粘贴到新文件中时,生成的静态 html 文件完全没问题。

我错过了什么?为什么我在 DOM 和它的渲染版本之间有这种差异?我该如何纠正?重新绘制?

当我使用带有 NS 后缀的函数版本(即 createElementNS 和 setAttributeNS(时,我得到类似的结果,但没有呈现任何内容。

这是罪魁祸首:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>bug dynamic svg</title>
<script type="text/javascript">
Element.prototype.grow = function (tag, attribute_map) {
var child = document.createElement(tag);
if ( attribute_map !== undefined ) {
for (let key in attribute_map) {
child.setAttribute(key, attribute_map[key]);
}
}
this.appendChild(child);
return child;
};
</script>
</head>
<body>
<div id="sandbox"><svg viewbox="0 0 200 200"></svg></div>
<script>
var g_svg = document.getElementById("sandbox").firstElementChild;
g_svg.grow('circle', {'cx':"100", 'cy':"100", 'r':"32"});
</script>
</html>

这是我通过检查器获得的 DOM 复制粘贴结果(手动删除脚本(:

<html><head>
<meta charset="utf-8">
<title>bug dynamic svg</title>
</head>
<body>
<div id="sandbox"><svg viewBox="0 0 200 200"><circle cx="100" cy="100" r="32"></circle></svg></div>
</body></html>

元素位于 SVG 命名空间中,属性通常不会。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>bug dynamic svg</title>
<script type="text/javascript">
Element.prototype.grow = function (tag, attribute_map) {
var child = document.createElementNS('http://www.w3.org/2000/svg', tag);
if ( attribute_map !== undefined ) {
for (let key in attribute_map) {
child.setAttribute(key, attribute_map[key]);
}
}
this.appendChild(child);
return child;
};
</script>
</head>
<body>
<div id="sandbox"><svg viewbox="0 0 200 200"></svg></div>
<script>
var g_svg = document.getElementById("sandbox").firstElementChild;
g_svg.grow('circle', {'cx':"100", 'cy':"100", 'r':"32"});
</script>
</html>

最新更新