javascript - 改变 svg 对象的颜色?

标签 javascript html svg

HTML:svg 对象和脚本应该更改 svg 对象的颜色,但由于某种原因却没有?

<object id="object" type="image/svg+xml" data="play-pattern--light.svg"></object>

       <script type="text/javascript">
        window.onload=function () {

            var a = document.getElementById("object");
            var svgDoc = a.contentDocument;
            var styleElement = svgDoc.createElementNS("http://www.w3.org/2000/svg", "style");
            styleElement.textContent = ".st0 { fill: #000 }";
            svgDoc.getElementById("object").appendChild(styleElement);
        };

      </script>

我认为这就是为 SVG 对象着色所需的全部内容

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="160px" height="160px" viewBox="0 0 160 160" style="enable-background:new 0 0 160 160;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#EDF5F5;}
</style>

需要一些指导,为什么我的代码无法工作,它还显示错误“Uncaught TypeError: Cannot read property 'appendChild' of null”

谢谢

最佳答案

您应该使用:

svgDoc.documentElement.appendChild(styleElement);

而不是

svgDoc.getElementById("object").appendChild(styleElement);

关于javascript - 改变 svg 对象的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804637/

相关文章:

javascript - 更改 SVG 填充循环

reactjs - React 中的 Snap.svg - 如何在生命周期方法中访问 svg?

javascript - 仅使用 JS 单击页面中任意位置时需要打印 Dom 路径

JavaScript element.classList.add ("fa fa-hand-rock-o") 错误 : "String contains an invalid character"

html - 阻止文本选择超出 div?

html - 使用基于网络的图像作为带有内联样式标签的背景,django

html - 从 Illustrator 文件导出的 SVG 中出现随机形状

php - 在固定的时间间隔后重新加载 div 的内容

javascript - 如何 trim 文本?

html - 2 固定导航栏全浏览器宽度和高度