繁体   English   中英

无法在 IE 中更改 SVG innerHTML

[英]Can't change SVG innerHTML in IE

我无法在 Internet Explorer 中使用 JavaScript 更改 svg 的 SVG 代码 (innerHTML)。

如果我去检查 IE 上的元素,并选择 svg,它只有:

<svg xmlns="http://www.w3.org/2000/svg" role="img" style="stroke-width: 0px;" viewBox="0 0 0 0" preserveAspectRatio="xMidYMid meet" type="shape"><g /></svg>

我使用的代码是:

document.getElementsByTagName("svg")[0].innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" role="img" style="stroke-width: 0px;" viewBox="0 0 880 400" preserveAspectRatio="xMidYMid meet" type="shape" height="400" width="880">
<rect width="100%" height="100%" fill="rgb(255,255,255)"/><rect x="0" y="0" width="81" height="81" fill="rgb(179,146,5)"/><rect x="560" y="160" width="81" height="81" fill="rgb(67,123,235)"/><rect x="0" y="80" width="81" height="81" fill="rgb(0,0,0)"/><rect x="80" y="80" width="81" height="81" fill="rgb(0,0,0)"/>
</svg>';

在 Chrome 中(例如)它显示了这样的 svg:例子

但在 IE 中,它只是空白。

正如您在@thebabydino 创建的@enxaneta 提供的链接中所见,您可以使用group.textContent = 'string'来更改 SVG 组的内容。 这不会使浏览器呈现内容,因此要在 HTML 元素中添加 SVG,我建议更改父元素的 innerHTML

 document.querySelector('.clear').addEventListener('click', function () { document.querySelector('g').textContent = ''; }); document.querySelector('.add').addEventListener('click', function () { document.querySelector('div').innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" role="img" style="stroke-width: 0px;" viewBox="0 0 880 400" preserveAspectRatio="xMidYMid meet" type="shape" height="400" width="880"><g><rect x="100" y="100" width="100" height="100" fill="rgb(67,123,235)"/></g></svg>'; });
 <button class="clear">Clear</button> <button class="add">Add</button> <div> <svg xmlns="http://www.w3.org/2000/svg" role="img" style="stroke-width: 0px;" viewBox="0 0 880 400" preserveAspectRatio="xMidYMid meet" type="shape" height="400" width="880"> <g> <rect x="100" y="100" width="100" height="100" fill="rgb(67,123,235)"/> </g> </svg> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM