javascript - 如何在创建 SVG 后插入一些元素?

标签 javascript jquery svg

<分区>

我已经创建了一个 SVG,现在我的问题是在两个 元素之间动态添加一些代码。

我怎样才能实现它?甚至 JS 或 jquery 都没问题!

DEMO

<svg width="500" height="500">  
  <circle id="circle1" class="sid" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" class="sid" cx="150" cy="50" r="20"  fill="green"/>
  <circle id="circle4" cx="350" class="sid" cy="50" r="20" fill="yellow"/>  
</svg>

$(document).ready(function() {
    $(".sid").mouseenter(function() {
      alert("I'm here");
$('#circle2').append('<circle id="circle3" cx="250" class="sid" cy="50" r="20" fill="blue"/>');  

     });
    $(".sid").mouseleave(function() {
       // action
     });
});

是否可以在元素之间添加少量代码而不是创建 SVG?

期待这样的输出。

<svg width="500" height="500">  
  <circle id="circle1" class="sid" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" class="sid" cx="150" cy="50" r="20"  fill="green"/>
  <circle id="circle3" cx="250" class="sid" cy="50" r="20" fill="blue"/>
  <circle id="circle4" cx="350" class="sid" cy="50" r="20" fill="yellow"/>  
</svg>

最佳答案

要创建 SVG 元素,您必须声明 namespace http://www.w3.org/2000/svg

这是一个演示:

$(document).ready(function() {
  $('svg').append(createSVG('circle', {
    id: "circle3",
    cx: 250,
    cy: 50,
    r: 20,
    fill: "blue",
    class: "sid"
  }));
});

function createSVG(tag, attrs) {
  var svg = document.createElementNS('http://www.w3.org/2000/svg', tag);
  for (var attr in attrs)
    svg.setAttribute(attr, attrs[attr]);
  return svg;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="500" height="500">  
  <circle id="circle1" class="sid" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" class="sid" cx="150" cy="50" r="20"  fill="green"/>
  <circle id="circle4" cx="350" class="sid" cy="50" r="20" fill="yellow"/>  
</svg>

或者将其解析为 XML 文档并附加 XML 中的 documentElement。

$(document).ready(function() {
  $("svg").append(
    $.parseXML(`<circle xmlns="http://www.w3.org/2000/svg" 
    id="circle3" cx="250" class="sid" 
    cy="50" r="20" fill="blue"/>`).documentElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="500" height="500">  
  <circle id="circle1" class="sid" cx="50" cy="50" r="20" fill="red"/>
  <circle id="circle2" class="sid" cx="150" cy="50" r="20"  fill="green"/>
  <circle id="circle4" cx="350" class="sid" cy="50" r="20" fill="yellow"/>  
</svg>

关于javascript - 如何在创建 SVG 后插入一些元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52548561/

相关文章:

函数内部的javascript变量指针

javascript - 在 keydown 上使用 jquery 跳过 tr 选择

android - VectorDrawable 图像变得像素化

javascript - 如何用图像替换 SVG 形状?

javascript - 在 javascript 中获取 textext 标签?

javascript - 在 Angularjs 中使用指令触发 ng-change

javascript - Google map js api 在纯 html 页面中工作正常,但在 asp.net mvc 页面中不起作用

php - woocommerce 自定义结帐字段添加费用以订购 ajax

jquery - 滚动菜单中 jQuery stop() 中的奇怪效果/闪烁

javascript - 用鼠标绘制 SVG