2016-09-13 9 views
0

あるdivから別のdivにsvg要素をコピーして貼り付ける必要があります。これを簡単に達成できる可能性はありますか?私は以下の方法で疲れました。あるdivから別のdivにsvg要素をコピーして貼り付けます

Circle = document.createElementNS("http://www.w3.org/2000/svg", tagName); 
      Circle.setAttribute("cx", x); 
      Circle.setAttribute("cy", y); 
      Circle.setAttribute("r", r); 
      Circle.setAttribute("stroke", s); 
      Circle.setAttribute("stroke-width", sw); 
      Circle.setAttribute("fill", fc); 

しかし、私はすべての要素を作成するのがより複雑であると感じています。以下では、参考のためにサンプルコードを追加しました。

HTML:

<div class="div1"> 
    <svg width="1000" height="1000"> 
     <g> 
      <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" /> 
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
      <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:purple" /> 
      <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" /> 
      <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" /> 
      <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" /> 
      <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3" /> 
      <path stroke="red" d="M5 20 l215 0" /> 
      <path stroke="black" d="M5 40 l215 0" /> 
      <path stroke="blue" d="M5 60 l215 0" /> 
     </g> 
    </svg> 
</div> 
<div class="div2"> 
    <svg width="1000" height="1000"> 
    </svg> 
</div> 
<a href="#">Click</a> 

Javascriptを:

$('a').click(function(){ 
    $('.div2 svg').append($('.div1 svg').html(); 
)}); 

答えて

1

あなたは第二のdivに追加したときにSVGを名前空間にありますので、あなたのコードは動作しません。

あなたはjQueryのを使用しているので、clone()が容易メソッドです:

$('a').click(function(){ 
 
    $('.div1 svg').clone().appendTo($('.div2')); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="div1"> 
 
    <svg width="400" height="200"> 
 
     <g> 
 
      <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" /> 
 
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
 
      <ellipse cx="240" cy="100" rx="220" ry="30" style="fill:purple" /> 
 
      <ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" /> 
 
      <ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" /> 
 
      <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" /> 
 
      <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3" /> 
 
      <path stroke="red" d="M5 20 l215 0" /> 
 
      <path stroke="black" d="M5 40 l215 0" /> 
 
      <path stroke="blue" d="M5 60 l215 0" /> 
 
     </g> 
 
    </svg> 
 
</div> 
 
<div class="div2"> 
 
</div> 
 
<a href="#">Click</a>

関連する問題