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/