2014-04-11 6 views
3

innerHTML을 사용하여 svg 요소를 추가했지만 크롬에서 제대로 작동하지만 Firefox에서는 표시 할 수 없습니다. 모든 ansower에게 감사드립니다.Firefox에서 svg innerHTML을 표시 할 수 없습니다.

<!DOCTYPE html> 
    <html> 
    <head> 
     <title>SVGInnerHTML demo</title> 
     <meta charset="utf-8" /> 
     <script src="svginnerhtml.js"></script> 
     <script> 
     alter = function() { 
      var svg = document.getElementById('container'); 

      svg.innerHTML = '<rect width="100" height="60" fill="green" />' 
          + '<circle cx="10" cy="19" r="20" fill="blue"></circle>' 
          + '<text x="15" y="20" fill="white">hello world</text>' 
          + '<g transform="translate(0, 70)"><rect width="100" height="20" fill="yellow" /></g>'; 
     } 
     </script> 
    </head> 

    <body> 

    <svg id="container" width="100px" height="100px" http://www.w3.org/2000/svg> 

    </svg> 

    <p> 
    <button onclick="alter()">set .innerHTML</button> 
    <button onclick="alert(document.getElementById('container').innerHTML)">get .innerHTML</button> 
    </p> 
    </body> 
    </html> 
+0

Firefox 36 이상에서는 정상적으로 작동합니다. –

답변

5

해결 방법은 innerHTML 코드를 SVG가 아닌 HTML로 추가하는 것입니다. HTML 코드에서 <div> (<svg> 대신)을 자리 표시 자로 사용하고 innerHTML을 통해 전체 SVG를 삽입하면됩니다.

<svg id="container" width="100px" height="100px"> 
</svg> 

<div id="container" style="width: 100px; height: 100px"> 
</div> 

로하고 <svg> 요소 내에서 innerHTML 문자열을 포장 :

는 교체

var svg = document.getElementById('container'); 
svg.innerHTML = '<svg><rect width="100" height="60" fill="green" />' 
       + '<circle cx="10" cy="19" r="20" fill="blue"></circle>' 
       + '<text x="15" y="20" fill="white">hello world</text>' 
       + '<g transform="translate(0, 70)">' 
       + '<rect width="100" height="20" fill="yellow" /></g></svg>'; 

이는 크롬과 파이어 폭스 모두에서 작동합니다. JSFiddle입니다.

+0

** 고마워요 ** ** – user3522022

+1

; 내 코드를 으로 바꾼다. var tempDiv = document.createElement ("div"); tempDiv.innerHTML = ""+ svgEles + "" var svgNodes = Array.prototype.slice.call (tempDiv.childNodes [0] .childNodes); svgNodes.forEach (function (el) { container.appendChild (el); }), ' 크롬과 파이어 폭스 모두에서 작동합니다. 덕분에 내 오래된 코드를 쉽게 고칠 수 있습니다. 감사합니다! – user3522022

+0

절대 위치 지정된 svg로 해결되지 않음 –

관련 문제