2016-03-04 140 views
1

HTML:svg对象和脚本,应该改变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> 

需要一些指导,为什么我的代码不能正常工作,它也说,一个错误“遗漏的类型错误:无法读取属性“的appendChild “空”的

感谢

回答

1

你应该使用:

svgDoc.documentElement.appendChild(styleElement); 

而不是

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