如何在JavaScript中将嵌入式精灵添加到DOM中


<!DOCTYPE html>
<html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
      svg{ display: inline-block; }
    </style>
    <script src="my.js"></script>
  </head>
  <body>
    <embed src="sprites.svg" type="image/svg+xml" width="0" height="0" />
    <svg id="MAIN" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 320 208" shape-rendering="crispEdges">
      <path d="M0 0h320v208h-320v-208z" fill="#000"/> <!-- Fill screen  -->
      <svg id="sprite1"><use xlink:href="sprites.svg#SP1" x="64" y="128"</use></svg>
      <svg id="sprite2"><use xlink:href="sprites.svg#SP2" x="64" y="128"</use></svg>
      <svg id="sprite3"><use xlink:href="sprites.svg#SP3" x="64" y="128"</use></svg>
    </svg>
    <script>
      start( 1 ); // Call Func in my.js
    </script>
  </body>
</html>

我在" Sprites.svg"中有数百个精灵。在JavaScript中,我如何通过JavaScript添加我想要的精灵。我希望它们添加它们,以便它们就像上面的示例HTML页面中的Sprite1到Sprite3,谢谢Keith

解决了它,不像我想象的那么复杂。

var svgURI  = "http://www.w3.org/2000/svg";
var mainSVG = document.getElementById( "MAIN" ); // my main SVG 
var svg     = document.createElementNS( svgURI, 'svg' );
svg.id      = "sprite4";
svg.innerHTML = "<use xlink:href='sprites.svg#SP4'></use>";
mainSVG.appendChild( svg );

感谢每个试图提供帮助的人

最新更新